|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import fastify from 'fastify'; |
| 3 | +import { getGraphQLParameters, processRequest, renderGraphiQL, shouldRenderGraphiQL } from 'graphql-helix'; |
| 4 | +import { envelop, useLogger, useSchema, useTiming } from '@envelop/core'; |
| 5 | +import { makeExecutableSchema } from '@graphql-tools/schema'; |
| 6 | + |
| 7 | +const schema = makeExecutableSchema({ |
| 8 | + typeDefs: /* GraphQL */ ` |
| 9 | + type Query { |
| 10 | + hello: String! |
| 11 | + } |
| 12 | + `, |
| 13 | + resolvers: { |
| 14 | + Query: { |
| 15 | + hello: () => 'World', |
| 16 | + }, |
| 17 | + }, |
| 18 | +}); |
| 19 | + |
| 20 | +const getEnveloped = envelop({ |
| 21 | + plugins: [useSchema(schema), useLogger(), useTiming()], |
| 22 | +}); |
| 23 | +const app = fastify(); |
| 24 | + |
| 25 | +app.route({ |
| 26 | + method: ['GET', 'POST'], |
| 27 | + url: '/graphql', |
| 28 | + async handler(req, res) { |
| 29 | + const { parse, validate, contextFactory, execute, schema } = getEnveloped({ req }); |
| 30 | + const request = { |
| 31 | + body: req.body, |
| 32 | + headers: req.headers, |
| 33 | + method: req.method, |
| 34 | + query: req.query, |
| 35 | + }; |
| 36 | + |
| 37 | + if (shouldRenderGraphiQL(request)) { |
| 38 | + res.type('text/html'); |
| 39 | + res.send(renderGraphiQL({})); |
| 40 | + } else { |
| 41 | + const { operationName, query, variables } = getGraphQLParameters(request); |
| 42 | + const result = await processRequest({ |
| 43 | + operationName, |
| 44 | + query, |
| 45 | + variables, |
| 46 | + request, |
| 47 | + schema, |
| 48 | + parse, |
| 49 | + validate, |
| 50 | + execute, |
| 51 | + contextFactory, |
| 52 | + }); |
| 53 | + |
| 54 | + if (result.type === 'RESPONSE') { |
| 55 | + res.status(result.status); |
| 56 | + res.send(result.payload); |
| 57 | + } else { |
| 58 | + // You can find a complete example with GraphQL Subscriptions and stream/defer here: |
| 59 | + // https://github.com/contrawork/graphql-helix/blob/master/examples/fastify/server.ts |
| 60 | + res.send({ errors: [{ message: 'Not Supported in this demo' }] }); |
| 61 | + } |
| 62 | + } |
| 63 | + }, |
| 64 | +}); |
| 65 | + |
| 66 | +app.listen(3000, () => { |
| 67 | + console.log(`GraphQL server is running in http://127.0.0.1:3000/graphql.`); |
| 68 | +}); |
0 commit comments