@as-integrations/cloudflare-workers
Version:
An integration to use Cloudflare Workers as a hosting service with Apollo Server v4
50 lines • 1.96 kB
JavaScript
import { HeaderMap, } from '@apollo/server';
export function startServerAndCreateCloudflareWorkersHandler(server, options) {
server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
const defaultContext = async () => ({});
const contextFunction = options?.context ?? defaultContext;
return async function cloudflareWorkersHandler(request, env, ctx) {
try {
if (request.method === 'OPTIONS') {
return new Response('', { status: 204 });
}
const httpGraphQLRequest = await normalizeIncomingRequest(request);
const { body, headers, status } = await server.executeHTTPGraphQLRequest({
httpGraphQLRequest: httpGraphQLRequest,
context: () => contextFunction({ request, env, ctx }),
});
if (body.kind === 'chunked') {
throw Error('Incremental delivery not implemented');
}
return new Response(body.string, {
status: status || 200,
headers: {
...Object.fromEntries(headers),
'content-length': Buffer.byteLength(body.string).toString(),
},
});
}
catch (e) {
return new Response(e.message, { status: 400 });
}
};
}
async function normalizeIncomingRequest(request) {
const headers = normalizeHeaders(request.headers);
const url = new URL(request.url);
const method = request.method.toUpperCase();
return {
method,
headers,
body: method === 'GET' ? request.body : await request.json(),
search: url.search ?? '',
};
}
function normalizeHeaders(headers) {
const headerMap = new HeaderMap();
headers.forEach((value, key) => {
headerMap.set(key, Array.isArray(value) ? value.join(', ') : value);
});
return headerMap;
}
//# sourceMappingURL=index.js.map