|
| 1 | +import type { Middleware } from 'koa'; |
| 2 | +import type { IncomingMessage } from 'http'; |
| 3 | +import { |
| 4 | + createHandler as createRawHandler, |
| 5 | + HandlerOptions, |
| 6 | + OperationContext, |
| 7 | +} from '../handler'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Create a GraphQL over HTTP Protocol compliant request handler for |
| 11 | + * the Koa framework. |
| 12 | + * |
| 13 | + * ```js |
| 14 | + * import Koa from 'koa'; // yarn add koa |
| 15 | + * import mount from 'koa-mount'; // yarn add koa-mount |
| 16 | + * import { createHandler } from 'graphql-http/lib/use/koa'; |
| 17 | + * import { schema } from './my-graphql-schema'; |
| 18 | + * |
| 19 | + * const app = new Koa(); |
| 20 | + * app.use(mount('/', createHandler({ schema }))); |
| 21 | + * |
| 22 | + * app.listen({ port: 4000 }); |
| 23 | + * console.log('Listening to port 4000'); |
| 24 | + * ``` |
| 25 | + * |
| 26 | + * @category Server/koa |
| 27 | + */ |
| 28 | +export function createHandler<Context extends OperationContext = undefined>( |
| 29 | + options: HandlerOptions<IncomingMessage, undefined, Context>, |
| 30 | +): Middleware { |
| 31 | + const isProd = process.env.NODE_ENV === 'production'; |
| 32 | + const handle = createRawHandler(options); |
| 33 | + return async function requestListener(ctx) { |
| 34 | + try { |
| 35 | + const [body, init] = await handle({ |
| 36 | + url: ctx.url, |
| 37 | + method: ctx.method, |
| 38 | + headers: ctx.headers, |
| 39 | + body: () => { |
| 40 | + if (ctx.body) { |
| 41 | + // in case koa has a body parser |
| 42 | + return ctx.body; |
| 43 | + } |
| 44 | + return new Promise<string>((resolve) => { |
| 45 | + let body = ''; |
| 46 | + ctx.req.on('data', (chunk) => (body += chunk)); |
| 47 | + ctx.req.on('end', () => resolve(body)); |
| 48 | + }); |
| 49 | + }, |
| 50 | + raw: ctx.req, |
| 51 | + context: undefined, |
| 52 | + }); |
| 53 | + ctx.body = body; |
| 54 | + ctx.response.status = init.status; |
| 55 | + ctx.response.message = init.statusText; |
| 56 | + if (init.headers) { |
| 57 | + for (const [name, value] of Object.entries(init.headers)) { |
| 58 | + ctx.response.set(name, value); |
| 59 | + } |
| 60 | + } |
| 61 | + } catch (err) { |
| 62 | + // The handler shouldnt throw errors. |
| 63 | + // If you wish to handle them differently, consider implementing your own request handler. |
| 64 | + console.error( |
| 65 | + 'Internal error occurred during request handling. ' + |
| 66 | + 'Please check your implementation.', |
| 67 | + err, |
| 68 | + ); |
| 69 | + ctx.response.status = 500; |
| 70 | + if (!isProd) { |
| 71 | + ctx.response.set('content-type', 'application/json; charset=utf-8'); |
| 72 | + ctx.body = { |
| 73 | + errors: [ |
| 74 | + err instanceof Error |
| 75 | + ? { |
| 76 | + message: err.message, |
| 77 | + stack: err.stack, |
| 78 | + } |
| 79 | + : err, |
| 80 | + ], |
| 81 | + }; |
| 82 | + } |
| 83 | + } |
| 84 | + }; |
| 85 | +} |
0 commit comments