UNPKG

@as-integrations/koa

Version:
62 lines 2.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.koaMiddleware = void 0; const node_stream_1 = require("node:stream"); const node_url_1 = require("node:url"); const server_1 = require("@apollo/server"); function koaMiddleware(server, options) { var _a; server.assertStarted('koaMiddleware()'); const defaultContext = async () => ({}); const context = (_a = options === null || options === void 0 ? void 0 : options.context) !== null && _a !== void 0 ? _a : defaultContext; return async (ctx) => { var _a; if (!ctx.request.body) { ctx.status = 500; ctx.body = '`ctx.request.body` is not set; this probably means you forgot to set up the ' + '`koa-bodyparser` middleware before the Apollo Server middleware.'; return; } const incomingHeaders = new server_1.HeaderMap(); for (const [key, value] of Object.entries(ctx.headers)) { if (value !== undefined) { incomingHeaders.set(key, Array.isArray(value) ? value.join(', ') : value); } } const httpGraphQLRequest = { method: ctx.method.toUpperCase(), headers: incomingHeaders, search: (_a = (0, node_url_1.parse)(ctx.url).search) !== null && _a !== void 0 ? _a : '', body: ctx.request.body, }; const { body, headers, status } = await server.executeHTTPGraphQLRequest({ httpGraphQLRequest, context: () => context({ ctx }), }); if (body.kind === 'complete') { ctx.body = body.string; } else if (body.kind === 'chunked') { ctx.body = node_stream_1.Readable.from((async function* () { for await (const chunk of body.asyncIterator) { yield chunk; if (typeof ctx.body.flush === 'function') { ctx.body.flush(); } } })()); } else { throw Error(`Delivery method ${body.kind} not implemented`); } if (status !== undefined) { ctx.status = status; } for (const [key, value] of headers) { ctx.set(key, value); } }; } exports.koaMiddleware = koaMiddleware; //# sourceMappingURL=index.js.map