Search code examples
graphqlapolloapollo-servergraphql-js

Migrating to 3.5.0 with apollo-server-express


I'm trying to update the version of one of my projects from node 12.x.x to node.14.x.x. Now I saw the documentation of apollo to migrate to the v3 but it's not clear at all someone know where to start? Is it gonna be easier to make all the apollo part systems from scratch? Current file that should be updated:

const { ApolloServer } = require('apollo-server-express');
const { makeExecutableSchema } = require('graphql-tools');
const { applyMiddleware } = require('graphql-middleware');
const { gql } = require('apollo-server-express');
const { resolvers, typeDefs } = require('graphql-scalars');

const { types } = require('./typedefs/types');
const { inputs } = require('./typedefs/inputs');
const { queries } = require('./typedefs/queries');
const { mutations } = require('./typedefs/mutations');

const customResolvers = require('./resolvers');
const { permissions } = require('./permissions/permissions');

const graphqlApis = gql`
  ${types}
  ${queries}
  ${inputs}
  ${mutations}
`;

const schema = makeExecutableSchema({
  typeDefs: [...typeDefs, graphqlApis],
  resolvers: {
    ...customResolvers,
    ...resolvers,
  },
});

const server = new ApolloServer({
  context: ({ req }) => {
    const headers = req.headers || '';
    return headers;
  },
  schema: applyMiddleware(schema, permissions),
});

module.exports = server;
Current error when trying to run: Error: You must 'await server.start()' before calling 'server.applyMiddleware()'

I would simply love to get some solutions/help/insight with it.


Solution

  • As mentioned in the docs, you need to surround your code with an Async function https://www.apollographql.com/docs/apollo-server/migration/

        (async function () {
           // ....
        })();
    

    Or Like so: ... define your typeDefs & resolvers first

    const typeDefs = "" // your typedefs here
    const resolvers = "" // your resolvers here
    async function startApolloServer(typeDefs, resolvers) {
      // Apollo Express 3.5.x code goes here
      // ....
      await server.start();
     // promise resolve...
    }
    startApolloServer(typeDefs, resolvers)