|
| 1 | +import { ApolloServer } from '@apollo/server'; |
| 2 | +import { |
| 3 | + ExpressContextFunctionArgument, |
| 4 | + expressMiddleware, |
| 5 | +} from '@apollo/server/express4'; |
| 6 | +import { buildSubgraphSchema } from '@apollo/subgraph'; |
| 7 | +import { GraphQLResolverMap } from '@apollo/subgraph/dist/schema-helper'; |
| 8 | +import { Opts } from '@internal/testing'; |
| 9 | +import cors from 'cors'; |
| 10 | +import express from 'express'; |
| 11 | +import { parse } from 'graphql'; |
| 12 | + |
| 13 | +const app = express(); |
| 14 | + |
| 15 | +const resolvers: GraphQLResolverMap<ExpressContextFunctionArgument> = { |
| 16 | + Query: { |
| 17 | + headers: (_source, _args, context) => { |
| 18 | + return { |
| 19 | + authorization: context.req.headers.authorization, |
| 20 | + sessionCookieId: context.req.headers['session-cookie-id'], |
| 21 | + }; |
| 22 | + }, |
| 23 | + }, |
| 24 | +}; |
| 25 | + |
| 26 | +const server = new ApolloServer<ExpressContextFunctionArgument>({ |
| 27 | + schema: buildSubgraphSchema({ |
| 28 | + typeDefs: parse(/* GraphQL */ ` |
| 29 | + type Query { |
| 30 | + headers: Headers! |
| 31 | + } |
| 32 | +
|
| 33 | + type Headers { |
| 34 | + authorization: String! |
| 35 | + sessionCookieId: String! |
| 36 | + } |
| 37 | + `), |
| 38 | + resolvers: resolvers as GraphQLResolverMap<unknown>, |
| 39 | + }), |
| 40 | +}); |
| 41 | + |
| 42 | +async function main() { |
| 43 | + // Note you must call `start()` on the `ApolloServer` |
| 44 | + // instance before passing the instance to `expressMiddleware` |
| 45 | + await server.start(); |
| 46 | + |
| 47 | + // Specify the path where we'd like to mount our server |
| 48 | + app.use( |
| 49 | + '/graphql', |
| 50 | + cors(), |
| 51 | + express.json(), |
| 52 | + // @ts-expect-error - Weird typing issue with `expressMiddleware` |
| 53 | + expressMiddleware(server, { context: (ctx) => ctx }), |
| 54 | + ); |
| 55 | + |
| 56 | + const opts = Opts(process.argv); |
| 57 | + |
| 58 | + app.listen(opts.getServicePort('upstream'), () => { |
| 59 | + console.log( |
| 60 | + `🚀 Server ready at http://localhost:${opts.getServicePort('upstream')}/graphql`, |
| 61 | + ); |
| 62 | + }); |
| 63 | +} |
| 64 | + |
| 65 | +main().catch((e) => { |
| 66 | + console.error(e); |
| 67 | + process.exit(1); |
| 68 | +}); |
0 commit comments