|
| 1 | +import { |
| 2 | + createHandler as createRawHandler, |
| 3 | + HandlerOptions as RawHandlerOptions, |
| 4 | + OperationContext, |
| 5 | +} from '../../handler'; |
| 6 | + |
| 7 | +import type { |
| 8 | + Handler as NetlifyHandler, |
| 9 | + HandlerEvent as NetlifyHandlerEvent, |
| 10 | + HandlerContext as NetlifyHandlerContext, |
| 11 | +} from '@netlify/functions'; |
| 12 | + |
| 13 | +/** |
| 14 | + * Handler options when using the netlify adapter |
| 15 | + * |
| 16 | + * @category Server/@netlify/functions |
| 17 | + */ |
| 18 | +export type HandlerOptions<Context extends OperationContext = undefined> = |
| 19 | + RawHandlerOptions<NetlifyHandlerEvent, NetlifyHandlerContext, Context>; |
| 20 | + |
| 21 | +/** |
| 22 | + * Create a GraphQL over HTTP spec compliant request handler for netlify functions |
| 23 | + * |
| 24 | + * @category Server/@netlify/functions |
| 25 | + */ |
| 26 | +export function createHandler<Context extends OperationContext = undefined>( |
| 27 | + options: HandlerOptions<Context>, |
| 28 | +): NetlifyHandler { |
| 29 | + const handler = createRawHandler(options); |
| 30 | + return async function handleRequest(req, ctx) { |
| 31 | + try { |
| 32 | + const [body, init] = await handler({ |
| 33 | + method: req.httpMethod, |
| 34 | + url: req.rawUrl, |
| 35 | + headers: req.headers, |
| 36 | + body: req.body, |
| 37 | + raw: req, |
| 38 | + context: ctx, |
| 39 | + }); |
| 40 | + return { |
| 41 | + // if body is null, return undefined |
| 42 | + body: body ?? undefined, |
| 43 | + statusCode: init.status, |
| 44 | + }; |
| 45 | + } catch (err) { |
| 46 | + // The handler shouldnt throw errors. |
| 47 | + // If you wish to handle them differently, consider implementing your own request handler. |
| 48 | + console.error( |
| 49 | + 'Internal error occurred during request handling. ' + |
| 50 | + 'Please check your implementation.', |
| 51 | + err, |
| 52 | + ); |
| 53 | + return { statusCode: 500 }; |
| 54 | + } |
| 55 | + }; |
| 56 | +} |
0 commit comments