|
| 1 | +import { ApolloServer } from '@apollo/server'; |
| 2 | +import { startStandaloneServer } from '@apollo/server/standalone'; |
| 3 | +import { Set } from '@nx-apollo/models-graphql'; |
| 4 | +import { readFileSync } from 'fs'; |
| 5 | +import { join } from 'path'; |
| 6 | +import { Resolvers } from './__generated__/resolvers'; |
| 7 | + |
| 8 | +// Note: this uses a path relative to the project's |
| 9 | +// root directory, which is the current working directory |
| 10 | +// if the server is executed using `npm run`. |
| 11 | +const typeDefs = readFileSync( |
| 12 | + join('libs/models-graphql/src/lib', 'schema.graphql'), |
| 13 | + { encoding: 'utf-8' } |
| 14 | +); |
| 15 | + |
| 16 | +const sets: Set[] = [ |
| 17 | + { |
| 18 | + id: 1, |
| 19 | + name: 'Voltron', |
| 20 | + numParts: 2300, |
| 21 | + year: '2019', |
| 22 | + }, |
| 23 | + { |
| 24 | + id: 2, |
| 25 | + name: 'Ship in a Bottle', |
| 26 | + numParts: 900, |
| 27 | + year: '2019', |
| 28 | + }, |
| 29 | +]; |
| 30 | + |
| 31 | +// Resolvers define how to fetch the types defined in your schema. |
| 32 | +// This resolver retrieves books from the "books" array above. |
| 33 | +const resolvers: Resolvers = { |
| 34 | + Query: { |
| 35 | + allSets: () => sets, |
| 36 | + }, |
| 37 | + Mutation: { |
| 38 | + addSet: (parent, args) => { |
| 39 | + const newSet = { |
| 40 | + id: sets.length + 1, |
| 41 | + name: args.name, |
| 42 | + year: args.year, |
| 43 | + numParts: +args.numParts, |
| 44 | + }; |
| 45 | + |
| 46 | + sets.push(newSet); |
| 47 | + |
| 48 | + return newSet; |
| 49 | + }, |
| 50 | + }, |
| 51 | +}; |
| 52 | + |
| 53 | +// The ApolloServer constructor requires two parameters: your schema |
| 54 | +// definition and your set of resolvers. |
| 55 | +const server = new ApolloServer({ |
| 56 | + typeDefs, |
| 57 | + resolvers, |
| 58 | +}); |
| 59 | + |
| 60 | +// Passing an ApolloServer instance to the `startStandaloneServer` function: |
| 61 | +// 1. creates an Express app |
| 62 | +// 2. installs your ApolloServer instance as middleware |
| 63 | +// 3. prepares your app to handle incoming requests |
| 64 | +const { url } = await startStandaloneServer(server, { |
| 65 | + listen: { port: 4000 }, |
| 66 | +}); |
| 67 | + |
| 68 | +console.log(`🚀 Server ready at: ${url}`); |
| 69 | + |
0 commit comments