Plugin the server to your express

getApolloServer

Call the function getApolloServer to get an instance of GNJ GraphQL server.

Here is a full example of a GNJ server plugged to an express app, including live subscription.

const { getApolloServer } = require('./../lib/index')
const express = require('express')
const http = require('spdy')
const { PubSub } = require('graphql-subscriptions')
const config = require('./sqliteTestConfig.js')
const app = express()

var options = {
  spdy: {
    plain: true
  }
}

const pubSubInstance = new PubSub()

const server = getApolloServer(config, { pubSubInstance })

/**
 * This is the test server.
 * Used to allow the access to the Graphql Playground at this address: http://localhost:8080/graphql.
 * Each time the server is starter, the database is reset.
 */
server.applyMiddleware({
  app,
  path: '/graphql'
})

const port = process.env.PORT || 8080

const serverHttp = http.createServer(options, app).listen(port, async () => {
  console.log(
    `🚀 http/https/h2 server runs on  http://localhost:${port}/graphql .`
  )
})

server.installSubscriptionHandlers(serverHttp)

You can add custom mutations to the GNJ server.

return getApolloServer(
    dbConfig,
    // Apollo server config: cache, extensions and co.
    {},
    // You can add custom mutations if needed
    {
      customAcquire: {
        type: new GraphQLObjectType({
          name: 'customAcquire',
          fields: {
            id: { type: GraphQLInt }
          }
        }),
        args: {
          typeList: {
            type: new GraphQLList(GraphQLString)
          }
        },
        resolve: async (source, args, context) => {
          // GNJ models can be retreived with the dbConfig if needed
          const models = getModels(dbConfig)
          // get a job from the db
          const job = await models.job.findByPk(1)

          return job
        }
      }
    }
  )

Last updated

Was this helpful?