2018-05-01 11:05:26 -07:00
|
|
|
import {
|
|
|
|
GraphQLOptions,
|
|
|
|
HttpQueryError,
|
|
|
|
runHttpQuery,
|
|
|
|
} from 'apollo-server-core';
|
|
|
|
|
|
|
|
// Design principles:
|
|
|
|
// - You can issue a GET or POST with your query.
|
|
|
|
// - simple, fast and secure
|
|
|
|
//
|
|
|
|
|
|
|
|
export function graphqlCloudflare(options: GraphQLOptions) {
|
|
|
|
if (!options) {
|
|
|
|
throw new Error('Apollo Server requires options.');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (arguments.length > 1) {
|
|
|
|
throw new Error(
|
|
|
|
`Apollo Server expects exactly one argument, got ${arguments.length}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2018-06-11 13:06:31 +02:00
|
|
|
const graphqlHandler = async (req: Request): Promise<Response> => {
|
|
|
|
const url = new URL(req.url);
|
2018-05-01 11:05:26 -07:00
|
|
|
const query =
|
|
|
|
req.method === 'POST'
|
2018-06-11 13:06:31 +02:00
|
|
|
? await req.json()
|
2018-05-01 11:05:26 -07:00
|
|
|
: {
|
|
|
|
query: url.searchParams.get('query'),
|
|
|
|
variables: url.searchParams.get('variables'),
|
|
|
|
operationName: url.searchParams.get('operationName'),
|
|
|
|
extensions: url.searchParams.get('extensions'),
|
|
|
|
};
|
|
|
|
|
|
|
|
return runHttpQuery([req], {
|
|
|
|
method: req.method,
|
|
|
|
options: options,
|
|
|
|
query,
|
2018-05-24 15:43:17 -07:00
|
|
|
request: req as Request,
|
2018-05-01 11:05:26 -07:00
|
|
|
}).then(
|
2018-06-21 13:29:14 -07:00
|
|
|
({ graphqlResponse, responseInit }) =>
|
|
|
|
new Response(graphqlResponse, responseInit),
|
2018-05-01 11:05:26 -07:00
|
|
|
(error: HttpQueryError) => {
|
|
|
|
if ('HttpQueryError' !== error.name) throw error;
|
|
|
|
|
2018-05-01 20:05:36 -07:00
|
|
|
const res = new Response(error.message, {
|
|
|
|
status: error.statusCode,
|
|
|
|
headers: { 'content-type': 'application/json' },
|
|
|
|
});
|
2018-05-01 11:05:26 -07:00
|
|
|
|
|
|
|
if (error.headers) {
|
|
|
|
Object.keys(error.headers).forEach(header => {
|
|
|
|
res.headers[header] = error.headers[header];
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
},
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
return graphqlHandler;
|
|
|
|
}
|