-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathgraphql.ts
60 lines (55 loc) · 1.75 KB
/
graphql.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import {
createHandler as createRawHandler,
HandlerOptions as RawHandlerOptions,
OperationContext,
} from 'graphql-http';
import type {
Handler as NetlifyHandler,
HandlerEvent as NetlifyHandlerEvent,
HandlerContext as NetlifyHandlerContext,
} from '@netlify/functions';
import schema from '../packages/graphiql/test/schema';
import { customExecute } from '../packages/graphiql/test/execute';
/**
* Handler options when using the netlify adapter
*
* @category Server/@netlify/functions
*/
export type HandlerOptions<Context extends OperationContext = undefined> =
RawHandlerOptions<NetlifyHandlerEvent, NetlifyHandlerContext, Context>;
/**
* Create a GraphQL over HTTP spec compliant request handler for netlify functions
*
* @category Server/@netlify/functions
*/
export function createHandler<Context extends OperationContext = undefined>(
options: HandlerOptions<Context>,
): NetlifyHandler {
const handler = createRawHandler(options);
return async function handleRequest(req, ctx) {
try {
const [body, init] = await handler({
method: req.httpMethod,
url: req.rawUrl,
headers: req.headers,
body: req.body,
raw: req,
context: ctx,
});
return {
// if body is null, return undefined
body: body ?? undefined,
statusCode: init.status,
};
} catch (err) {
// The handler shouldn't throw errors.
// If you wish to handle them differently, consider implementing your own request handler.
console.error(
'Internal error occurred during request handling. Please check your implementation.',
err,
);
return { statusCode: 500 };
}
};
}
export const handler = createHandler({ schema, execute: customExecute });