apollo-server-express#ApolloServerExpressConfig TypeScript Examples

The following examples show how to use apollo-server-express#ApolloServerExpressConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: graphql.ts    From OpenVolunteerPlatform with MIT License 6 votes vote down vote up
createApolloServer = async function (app: Express, config: Config) {
    const db = await connect(config);

    const modelDefs = loadSchemaSync(resolve(__dirname, '../model/main.graphql'), {
        loaders: [
            new GraphQLFileLoader()
        ]
    })

    const { typeDefs, resolvers, contextCreator } = buildGraphbackAPI(modelDefs, {
        serviceCreator: createKeycloakCRUDService(authConfig),
        dataProviderCreator: createMongoDbProvider(db)
    });
    // TODO enable custom resolvers
    const mergedResolvers: any = GMR.merge([resolvers, customResolvers]);
    let apolloConfig: ApolloServerExpressConfig = {
        typeDefs: typeDefs,
        resolvers: mergedResolvers,
        playground: true,
        context: (context) => {
            return {
                ...contextCreator(context),
                db: db
            }
        }
    }

    if (config.keycloakConfig) {
        apolloConfig = buildKeycloakApolloConfig(app, apolloConfig)
    }

    const apolloServer = new ApolloServer(apolloConfig)
    apolloServer.applyMiddleware({ app });

    return apolloServer;
}
Example #2
Source File: index.ts    From Next.js_GraphQL_Express_Apollo_Boilerplate with MIT License 6 votes vote down vote up
schema: ApolloServerExpressConfig = {
  typeDefs,
  resolvers,
  introspection: true,
  context: async ({ req, connection, payload }: any) => {
    if (connection) {
      return { isAuth: payload.authToken };
    }
    return { isAuth: req.isAuth };
  },
  playground: true
}
Example #3
Source File: app.ts    From cloud-pricing-api with Apache License 2.0 5 votes vote down vote up
async function createApp(opts: ApplicationOptions = {}): Promise<Application> {
  const app = express();

  const logger = opts.logger || config.logger;

  if (!opts.disableRequestLogging) {
    app.use(
      pinoHttp({
        logger,
        customLogLevel(res, err) {
          if (err || res.statusCode === 500) {
            return 'error';
          }
          return 'info';
        },
        autoLogging: {
          ignorePaths: ['/health'],
        },
      })
    );
  }

  if (!opts.disableStats) {
    app.use(express.static(path.join(__dirname, 'public')));
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(home);
  }

  app.use(express.json());
  app.use(
    (err: ResponseError, _req: Request, res: Response, next: NextFunction) => {
      if (err instanceof SyntaxError && err.status === 400) {
        res.status(400).send({ error: 'Bad request' });
      } else {
        next();
      }
    }
  );

  if (!opts.disableRequestLogging) {
    app.use((req: Request, _res: Response, next: NextFunction) => {
      if (!['/health', '/graphql'].includes(req.path)) {
        logger.debug({ body: req.body });
      }
      next();
    });
  }

  app.use(health);

  if (!opts.disableAuth) {
    app.use(auth);
  }

  if (!opts.disableStats) {
    app.use(events);
    app.use(stats);
  }

  const apolloConfig: ApolloServerExpressConfig = {
    schema: makeExecutableSchema({
      typeDefs,
      resolvers,
    }),
    introspection: true,
    plugins: [
      ApolloServerPluginLandingPageGraphQLPlayground(),
      () => new ApolloLogger(logger),
    ],
    ...opts.apolloConfigOverrides,
  };

  const apollo = new ApolloServer(apolloConfig);
  await apollo.start();

  apollo.applyMiddleware({ app });

  return app;
}
Example #4
Source File: index.ts    From fullstack-starterkit with MIT License 5 votes vote down vote up
GraphQLServerOptions: ApolloServerExpressConfig = {
  schema,
  context: (context: ExpressContext) => ({
    ...context,
    prisma,
    logger
  })
}
Example #5
Source File: server.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
@def
    async config(): Promise<ApolloServerExpressConfig> {
        let plugins: PluginDefinition[] = []
        let typeDefs = [buildServerSchema(this.model(), this.dialect())]
        let resolvers = buildResolvers(this.model(), this.dialect())

        let requestCheck = this.customCheck()
        if (requestCheck) {
            plugins.push(createCheckPlugin(requestCheck, this.model()))
        }

        let context: () => ResolverContext

        let customResolvers = await this.customResolvers()
        if (customResolvers) {
            typeDefs.push(customResolvers.typeDefs)
            resolvers = mergeResolvers([resolvers, customResolvers.resolvers])
            context = () => this.createTypeormResolverContext()
        } else {
            context = () => this.createPoolResolverContext()
        }

        plugins.push({
            serverWillStart: async () => {
                if (customResolvers) {
                    this.db = await this.typeormConnection()
                } else {
                    this.db = this.pgPool()
                }
                return {
                    serverWillStop: async () => {
                        if (this.db == null) return
                        if (this.db instanceof Pool) {
                            await this.db.end()
                        } else {
                            await this.db.close()
                        }
                    }
                }
            },
            async requestDidStart() {
                return {
                    willSendResponse(req: any) {
                        return req.context.openReaderTransaction.close()
                    }
                }
            }
        })

        plugins.push(
            ApolloServerPluginDrainHttpServer({httpServer: this.httpServer()})
        )

        return {
            typeDefs,
            resolvers,
            context,
            plugins
        }
    }