|
| 1 | +// npm install @apollo/server express graphql cors body-parser |
| 2 | +import http from 'http'; |
| 3 | +import { ApolloServer } from '@apollo/server'; |
| 4 | +import { expressMiddleware } from '@apollo/server/express4'; |
| 5 | +import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer'; |
| 6 | +import express from 'express'; |
| 7 | +import cors from 'cors'; |
| 8 | +import bodyParser from 'body-parser'; |
| 9 | + |
| 10 | +interface MyContext { |
| 11 | + token?: String |
| 12 | +} |
| 13 | +// Construct a schema, using GraphQL schema language |
| 14 | +const typeDefs = ` |
| 15 | + type Query { |
| 16 | + hello: String |
| 17 | + } |
| 18 | +`; |
| 19 | + |
| 20 | +// Provide resolver functions for your schema fields |
| 21 | +const resolvers = { |
| 22 | + Query: { |
| 23 | + hello: () => 'Hello world!~!', |
| 24 | + }, |
| 25 | +}; |
| 26 | + |
| 27 | +async function bootstrap() { |
| 28 | + // Required logic for integrating with Express |
| 29 | + const app = express(); |
| 30 | + // Our httpServer handles incoming requests to our Express app. |
| 31 | + // Below, we tell Apollo Server to "drain" this httpServer, |
| 32 | + // enabling our servers to shut down gracefully. |
| 33 | + const httpServer = http.createServer(app); |
| 34 | + |
| 35 | + // Same ApolloServer initialization as before, plus the drain plugin |
| 36 | + // for our httpServer. |
| 37 | + const server = new ApolloServer<MyContext>({ |
| 38 | + typeDefs, |
| 39 | + resolvers, |
| 40 | + plugins: [ApolloServerPluginDrainHttpServer({ httpServer })], |
| 41 | + }); |
| 42 | + // Ensure we wait for our server to start |
| 43 | + await server.start(); |
| 44 | + |
| 45 | + // Set up our Express middleware to handle CORS, body parsing, |
| 46 | + // and our expressMiddleware function. |
| 47 | + app.use( |
| 48 | + '/', |
| 49 | + cors<cors.CorsRequest>(), |
| 50 | + bodyParser.json(), |
| 51 | + // expressMiddleware accepts the same arguments: |
| 52 | + // an Apollo Server instance and optional configuration options |
| 53 | + expressMiddleware(server, { |
| 54 | + context: async ({ req }) => ({ token: req.headers.token }), |
| 55 | + }), |
| 56 | + ); |
| 57 | + |
| 58 | + if (import.meta.env.PROD) { |
| 59 | + // Modified server startup |
| 60 | + httpServer.listen(3000); |
| 61 | + } |
| 62 | + |
| 63 | + return app; |
| 64 | +} |
| 65 | +const app = bootstrap(); |
| 66 | +export const viteNodeApp = app; |
0 commit comments