apollo-server-express#ApolloServer TypeScript Examples

The following examples show how to use apollo-server-express#ApolloServer. 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: index.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
(async function () {
  const app = express();
  app.use(express.json());
  const graphqlServer = new ApolloServer({
    typeDefs,
    resolvers,
    plugins: [
      process.env.NODE_ENV === 'production'
        ? ApolloServerPluginLandingPageDisabled()
        : ApolloServerPluginLandingPageGraphQLPlayground(),
    ],
  });
  await graphqlServer.start();
  graphqlServer.applyMiddleware({ app });

  const publicPath = path.resolve(__dirname, './public');
  app.use(express.static(publicPath));
  app.use('/api/hotels', hotelApi);
  app.use('/api/cities', cityApi);

  app.listen(PORT, () => {
    console.log(`Server running http://localhost:${PORT}`);
    console.log(
      `GraphQL server ready at http://localhost:${PORT}${graphqlServer.graphqlPath}`
    );
  });
})();
Example #2
Source File: server.ts    From opensaas with MIT License 6 votes vote down vote up
async function main() {
  const server = new ApolloServer({
    gateway,
    context: ({ req: { headers } }) => ({ headers }),
    subscriptions: false,
  });
  server.applyMiddleware({ app });
  app.listen({ port: APP_PORT });
}
Example #3
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
apolloServer = new ApolloServer({
    schema,
    context: injectContext,
    plugins,
    // As this repository is open source anyways, there is no sense in keeping our graph private ("security by obscurity" doesn't work anyways)
    introspection: true,
    debug: isDev,
    formatError
})
Example #4
Source File: server.ts    From opensaas with MIT License 6 votes vote down vote up
async function main() {
  await connectDB(DB_URI || '');
  const context = ({ req }: Context) => {
    return { tenantId: req.headers[TENANT_HEADER] || '' };
  };
  const server = new ApolloServer({ schema, context });
  server.applyMiddleware({ app });
  app.listen({ port: APP_PORT });
}
Example #5
Source File: server.ts    From opensaas with MIT License 6 votes vote down vote up
async function main() {
  await createConnection();
  const schema = await buildFederatedSchema({ resolvers: [RequestResolver] });
  const context = ({ req }: Context) => {
    return { tenantId: req.headers[TENANT_HEADER] || '' };
  };
  const server = new ApolloServer({ schema, context });
  server.applyMiddleware({ app });
  app.listen({ port: APP_PORT });
}
Example #6
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 #7
Source File: index.ts    From liferay-grow with MIT License 6 votes vote down vote up
private async initializeApollo(): Promise<void> {
    const apolloServerConfig = await ApolloConfig.getApolloConfig();

    const apolloServer = new ApolloServer(apolloServerConfig);

    apolloServer.applyMiddleware({
      app: this.express,
      cors: true,
    });
  }
Example #8
Source File: index.ts    From tinyhouse with MIT License 6 votes vote down vote up
async function mount(app: Application) {
    const db = await connectDatabase();

    app.use(cookieParser(process.env.SECRET));

    const server = new ApolloServer({
        typeDefs,
        resolvers,
        context: ({ req, res }) => ({ db, req, res }),
    });
    await server.start();
    server.applyMiddleware({ app, path: "/api" });

    app.listen(port);

    console.log(`[app]: http://localhost:${port}`);
}
Example #9
Source File: index.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
export async function createServer(schemaPath: any, mockRest = true, allowInvalidCreds = true) {
  let typeDefs
  try {
    typeDefs = await readFileSync(schemaPath).toString('utf-8');
  } catch (ex) {
    throw new Error(`Unable to read ${schemaPath}, please specify correct path to grapqhl schema file using --schema option`)
  }

  const expressApp = express();
  
  const apolloServer = new ApolloServer({
    typeDefs,
    mocks,
    resolvers: mockedResolvers(gql`${typeDefs}`),
    mockEntireSchema: false
  });
  await apolloServer.start();

  apolloServer.applyMiddleware({app: expressApp});
  expressApp.use(express.urlencoded({extended: false}), express.json())
  expressApp.use(createOauthRouter(allowInvalidCreds))
  if (mockRest) {
    expressApp.use(restRouter)
  }

  return {expressApp, apolloServer};
}
Example #10
Source File: graphql.ts    From the-fake-backend with ISC License 6 votes vote down vote up
applyMiddlewareTo(app: express.Application): ApolloServer {
    const serverOptions = {
      typeDefs: this.typeDefs,
    };

    const serverOptionsEnhanced = this.generateQueriesAndMutations(
      serverOptions
    );

    const server: ApolloServer = new ApolloServer(serverOptionsEnhanced);

    const middlewareOptions = { app };

    server.applyMiddleware(middlewareOptions);

    return server;
  }
Example #11
Source File: apollo-server.ts    From clean-ts-api with GNU General Public License v3.0 6 votes vote down vote up
setupApolloServer = (): ApolloServer => new ApolloServer({
  schema,
  context: ({ req }) => ({ req }),
  plugins: [{
    requestDidStart: async () => ({
      willSendResponse: async ({ response, errors }) => handleErrors(response, errors)
    })
  }]
})
Example #12
Source File: index.ts    From type-graphql-dataloader with MIT License 6 votes vote down vote up
export async function listen(
  port: number,
  resolvers: NonEmptyArray<Function>
): Promise<ListenResult> {
  const app = express();

  const schema = await buildSchema({
    resolvers,
  });

  const apollo = new ApolloServer({
    schema,
    plugins: [
      ApolloServerLoaderPlugin({
        typeormGetConnection: getConnection,
      }),
    ],
  });
  await apollo.start();

  apollo.applyMiddleware({ app, cors: false });

  const server = http.createServer(app);
  await promisify(server.listen.bind(server, port))();

  return {
    port: (server.address() as AddressInfo).port,
    close: promisify(server.close).bind(server),
  };
}
Example #13
Source File: server.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
@def
    async start(): Promise<ListeningServer> {
        let app = this.app()
        let cfg = await this.config()
        let apollo = new ApolloServer(cfg)

        await apollo.start()

        try {
            setupGraphiqlConsole(app)
            apollo.applyMiddleware({app})
            return await listen(apollo, this.httpServer(), this.getPort())
        } catch(e: any) {
            await apollo.stop().catch(err => {
                e = new Error(e.stack + '\n\n' + err.stack)
            })
            throw e
        }
    }
Example #14
Source File: service.ts    From one-platform with MIT License 6 votes vote down vote up
apolloServer = new ApolloServer({
  schema,
  formatError: (error) => ({
    message: error.message,
    locations: error.locations,
    path: error.path,
    ...error.extensions,
  }),
  plugins: [
    {
      requestDidStart: (requestContext):any => {
        if (requestContext.request.http?.headers.has('x-apollo-tracing')) {
          return;
        }
        const query = requestContext.request.query?.replace(/\s+/g, ' ').trim();
        const variables = JSON.stringify(requestContext.request.variables);
        Logger.http(
          `${new Date().toISOString()}- [Request Started] { query: ${query}, variables: ${variables}, operationName: ${
            requestContext.request.operationName
          } }`,
        );
      },
    },
  ],
})
Example #15
Source File: service.ts    From one-platform with MIT License 6 votes vote down vote up
apolloServer = new ApolloServer({
  schema,
  formatError: (error) => ({
    message: error.message,
    locations: error.locations,
    path: error.path,
    ...error.extensions,
  }),
  plugins: [
    {
      requestDidStart: (requestContext):any => {
        if (requestContext.request.http?.headers.has('x-apollo-tracing')) {
          return;
        }
        const query = requestContext.request.query?.replace(/\s+/g, ' ').trim();
        const variables = JSON.stringify(requestContext.request.variables);
        logger.info(`${new Date().toISOString()}- [Request Started] { query: ${query}, variables: ${variables}, operationName: ${
          requestContext.request.operationName
        } }`);
      },
    },
  ],
})
Example #16
Source File: service.ts    From one-platform with MIT License 6 votes vote down vote up
apolloServer = new ApolloServer({
  schema,
  formatError: (error) => ({
    message: error.message,
    locations: error.locations,
    path: error.path,
    ...error.extensions,
  }),
  plugins: [
    {
      requestDidStart: (requestContext):any => {
        if (requestContext.request.http?.headers.has('x-apollo-tracing')) {
          return;
        }
        const query = requestContext.request.query?.replace(/\s+/g, ' ').trim();
        const variables = JSON.stringify(requestContext.request.variables);
        Logger.http(
          `- [Request Started] { query: ${query}, variables: ${variables}, operationName: ${
            requestContext.request.operationName
          } }`,
        );
      },
    },
  ],
})
Example #17
Source File: service.ts    From one-platform with MIT License 6 votes vote down vote up
apolloServer = new ApolloServer({
  schema,
  formatError: (error) => ({
    message: error.message,
    locations: error.locations,
    path: error.path,
    ...error.extensions,
  }),
  plugins: [
    {
      requestDidStart: (requestContext): any => {
        if (requestContext.request.http?.headers.has('x-apollo-tracing')) {
          return;
        }
        const query = requestContext.request.query?.replace(/\s+/g, ' ').trim();
        const variables = JSON.stringify(requestContext.request.variables);
        Logger.http(
          `${new Date().toISOString()}- [Request Started] { query: ${query}, variables: ${variables}, operationName: ${
            requestContext.request.operationName
          } }`,
        );
      },
    },
  ],
})
Example #18
Source File: server.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
export async function serve(options: ServerOptions): Promise<ListeningServer> {
    let {model, db} = options
    let dialect = options.dialect ?? 'postgres'
    let resolvers = buildResolvers(model, dialect)
    let typeDefs = buildServerSchema(model, dialect)
    let app = express()
    let server = http.createServer(app)

    let apollo = new ApolloServer({
        typeDefs,
        resolvers,
        context: () => ({openReaderTransaction: new PoolTransaction(db)}),
        plugins: [
            {
                async requestDidStart() {
                    return {
                        willSendResponse(req: any) {
                            return req.context.openReaderTransaction.close()
                        }
                    }
                }
            },
            ApolloServerPluginDrainHttpServer({httpServer: server})
        ]
    })

    if (options.graphiqlConsole !== false) {
        setupGraphiqlConsole(app)
    }

    await apollo.start()
    apollo.applyMiddleware({app})
    return listen(apollo, server, options.port)
}
Example #19
Source File: server.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
export function listen(apollo: ApolloServer, server: http.Server, port: number | string): Promise<ListeningServer> {
    return new Promise((resolve, reject) => {
        function onerror(err: Error) {
            cleanup()
            reject(err)
        }

        function onlistening() {
            cleanup()
            let address = server.address()
            assert(address != null && typeof address == 'object')
            resolve({
                port: address.port,
                stop: () => apollo.stop()
            })
        }

        function cleanup() {
            server.removeListener('error', onerror)
            server.removeListener('listening', onlistening)
        }

        server.on('error', onerror)
        server.on('listening', onlistening)
        server.listen(port)
    })
}
Example #20
Source File: index.ts    From lireddit with MIT License 5 votes vote down vote up
main = async () => {
  const conn = await createConnection({
    type: "postgres",
    url: process.env.DATABASE_URL,
    logging: true,
    // synchronize: true,
    migrations: [path.join(__dirname, "./migrations/*")],
    entities: [Post, User, Updoot],
  });
  // await conn.runMigrations();

  // await Post.delete({});

  const app = express();

  const RedisStore = connectRedis(session);
  const redis = new Redis(process.env.REDIS_URL);
  app.set("trust proxy", 1);
  app.use(
    cors({
      origin: process.env.CORS_ORIGIN,
      credentials: true,
    })
  );
  app.use(
    session({
      name: COOKIE_NAME,
      store: new RedisStore({
        client: redis,
        disableTouch: true,
      }),
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 365 * 10, // 10 years
        httpOnly: true,
        sameSite: "lax", // csrf
        secure: __prod__, // cookie only works in https
        domain: __prod__ ? ".codeponder.com" : undefined,
      },
      saveUninitialized: false,
      secret: process.env.SESSION_SECRET,
      resave: false,
    })
  );

  const apolloServer = new ApolloServer({
    schema: await buildSchema({
      resolvers: [HelloResolver, PostResolver, UserResolver],
      validate: false,
    }),
    context: ({ req, res }) => ({
      req,
      res,
      redis,
      userLoader: createUserLoader(),
      updootLoader: createUpdootLoader(),
    }),
  });

  apolloServer.applyMiddleware({
    app,
    cors: false,
  });

  app.listen(parseInt(process.env.PORT), () => {
    console.log("server started on localhost:4000");
  });
}
Example #21
Source File: index.ts    From graphql-schema-registry with MIT License 5 votes vote down vote up
server = new ApolloServer({
	typeDefs,
	resolvers,
	context: () => ({
		dataloaders: dataloader(),
	}),
})
Example #22
Source File: index.ts    From ledokku with MIT License 5 votes vote down vote up
apolloServer = new ApolloServer({
  typeDefs,
  resolvers: {
    ...resolvers,
    DateTime: DateTimeResolver,
  },
  subscriptions: {
    onConnect: async (context: SubscriptionContext) => {
      if (!context.token) {
        throw new Error('Missing auth token');
      }
      try {
        const decoded = jsonwebtoken.verify(
          context.token,
          config.jwtSecret
        ) as {
          userId: string;
        };
        const userId = decoded.userId;

        const userInDb = await prisma.user.findUnique({
          where: {
            id: userId,
          },
        });
        if (!userInDb) throw new Error("User doesn't exist in our db");
      } catch (e) {
        throw new Error('Invalid token');
      }
    },
  },

  context: ({ req, connection }) => {
    if (connection) {
      return connection.context;
    }
    const token =
      req.headers['authorization'] &&
      (req.headers['authorization'] as string).replace('Bearer ', '');

    let userId: string | undefined;
    try {
      const decoded = jsonwebtoken.verify(token, config.jwtSecret) as {
        userId: string;
      };
      userId = decoded.userId;
    } catch (err) {
      // Invalid token
    }
    return {
      userId,
    };
  },
})
Example #23
Source File: index.ts    From fullstack-starterkit with MIT License 5 votes vote down vote up
server: ApolloServer = new ApolloServer(GraphQLServerOptions)
Example #24
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 #25
Source File: express.ts    From Next.js_GraphQL_Express_Apollo_Boilerplate with MIT License 5 votes vote down vote up
public server: ApolloServer = new ApolloServer(schema);
Example #26
Source File: index.ts    From Wern-Fullstack-Template with MIT License 5 votes vote down vote up
main = async () => {
  console.log(process.env.DATABASE_URL)
  /*const conn =*/ await createConnection({
    type: 'postgres',
    url: process.env.DATABASE_URL,
    logging: true,
    //  do not want synchronize true in production, possiblility of losing data
    synchronize: false,
    entities: [UserAccount],
    migrations: [path.join(__dirname, './migrations/*')],
    //  need this to use postgres heroku plugin
    ssl: {
      rejectUnauthorized: false,
    },
  })
  // await conn.runMigrations()

  const app = express()

  app.set('trust proxy', 1)
  app.use(
    cors({
      origin: process.env.CORS_ORIGIN,
      credentials: true,
    })
  )

  const apolloServer = new ApolloServer({
    schema: await buildSchema({
      resolvers: [UserResolver],
      validate: false,
    }),
    context: ({ req, res }) => ({
      req,
      res,
    }),
  })

  apolloServer.applyMiddleware({
    app,
    cors: false,
    path: '/',
  })

  app.listen(parseInt(process.env.PORT!), () => {
    console.log(`server started on localhost:${process.env.PORT!}`)
  })
}
Example #27
Source File: express.ts    From bouncecode-cms with GNU General Public License v3.0 5 votes vote down vote up
server = new ApolloServer({
  schema,
  context,
})
Example #28
Source File: service.ts    From one-platform with MIT License 5 votes vote down vote up
stitchedSchemas()
  .then( schema => {
    /* Defining the Apollo Server */
    const apollo = new ApolloServer( {
      subscriptions: {
        path: subsciptionsBaseUrl,
      },
      schema,
      context,
      introspection: true,
      tracing: process.env.NODE_ENV !== 'production',
      playground: <any>{
        title: 'API Gateway',
        settings: {
          'request.credentials': 'include'
        },
        headers: {
          Authorization: `Bearer <ENTER_API_KEY_HERE>`, /* lgtm [js/hardcoded-credentials] */
        },
      },
      plugins: [
        {
          requestDidStart: ( requestContext ) => {
            if ( requestContext.request.http?.headers.has( 'x-apollo-tracing' ) ) {
              return;
            }
            console.log( new Date().toISOString(), `- Incoming ${ requestContext.request.http?.method } request from: ${ requestContext.request.http?.headers.get( 'origin' ) || 'unknown' }`, `- via ${ requestContext.request.http?.headers.get( 'user-agent' ) }` );
          }
        }
      ],
      formatError: error => ( {
        message: error.message,
        locations: error.locations,
        path: error.path,
        ...error.extensions,
      } ),
    } );

    /* Applying apollo middleware to express server */
    apollo.applyMiddleware( { app, path: baseUrl } );
    apollo.installSubscriptionHandlers( server );
  } )
  .catch( err => {
    console.error( err );
    throw err;
  } );
Example #29
Source File: router.ts    From backstage with Apache License 2.0 5 votes vote down vote up
export async function createRouter(
  options: RouterOptions,
): Promise<express.Router> {
  const catalogModule = await createCatalogModule(options);

  const { createSchemaForApollo } = createApplication({
    modules: [catalogModule],
    schemaBuilder(input) {
      return makeExecutableSchema({
        ...input,
        inheritResolversFromInterfaces: true,
      });
    },
  });

  const server = new ApolloServer({
    schema: createSchemaForApollo(),
    logger: options.logger,
    introspection: true,
  });

  await server.start();

  const router = Router();

  router.get('/health', (_, response) => {
    response.send({ status: 'ok' });
  });

  const apolloMiddleware = server.getMiddleware({ path: '/' });

  if (process.env.NODE_ENV === 'development')
    router.use(
      helmet.contentSecurityPolicy({
        directives: {
          defaultSrc: ["'self'", "'unsafe-inline'", 'http://*'],
        },
      }),
    );

  router.use(apolloMiddleware);
  router.use(errorHandler());

  return router;
}