NodeBB and Apollo GraphQL

Plugin Development
  • Hi,

    I am trying to add a route into NodeBB to serve GraphQL API.
    After doing some research on Google, I find a popular package named Apollo GraphQL, which has a document to show how to integrate Apollo GraphQL server with existing Express server, can help me to do my job.

    Then, I tried to create a plugin and put the example code of graphql with a route path:/mygraphql into my library.js. But, the nodebb keep returning 404 Not found. Did I do anything wrong?

    Here is what my library.js looks like:

    const { ApolloServer, gql } = require('apollo-server-express');
    
    const books = [
    	{
    		title: 'Harry Potter and the Chamber of Secrets',
    		author: 'J.K. Rowling',
    	},
    	{
    		title: 'Jurassic Park',
    		author: 'Michael Crichton',
    	},
    ];
    
    const typeDefs = gql`
      type Book {
        title: String
        author: String
      }
    
      type Query {
        books: [Book]
      }
    `;
    
    const resolvers = {
    	Query: {
    		books: () => books,
    	},
    };
    
    const apolloServer = new ApolloServer({
    	typeDefs,
    	resolvers,
    });
    
    
    const plugin = {};
    
    plugin.init = function (params, callback) {
    	const app = params.app;
    
    	apolloServer.applyMiddleware({
    		app,
    		path: '/api/mygraphql',
    	});
    
    	callback();
    };
    
    module.exports = plugin;
    

    Thanks!

  • Does Apollo have to be injected as a middleware? What app is, when passed to plugins, is not actually the express app, but a Router instance.

    That might be the crux of your problem, but I am not 100% sure.

  • @julian thanks for your reply.

    The reason why I inject Apollo as a middleware is because of the server integrate document on Apollo website shows that we can use the apollo-server-express package to integrate GraphQL with existing Express server by adding following code:

    server.applyMiddleware({ app }); // app is from an existing express app
    

    Does router will be the express app to be passed to plugins? Because I solved this problem by passing router into .applyMiddleware() method as following changes:

    const router = params.router;
    
    apolloServer.applyMiddleware({
        app: router,
        path: '/api/mygraphql',
    });
    

    Now, the GraphQL works fine on my NodeBB server ! Hope this can help someone who run into the same problem like me. Although it looks like GraphQL is not popular in NodeBB community 🤔.


Suggested Topics