UNPKG

@fanoutio/apollo-server-lambda-grip

Version:

Apollo Server that runs on AWS Lambda API Gateway and GRIP to pump subscriptions

85 lines 2.7 kB
import http from "http"; export function httpFromApiGatewayEvent(event) { const lowerHeaders = {}; for (const [key, value] of Object.entries(event.headers)) { lowerHeaders[key.toLowerCase()] = value; } const req = { headers: lowerHeaders, method: event.httpMethod, body: event.body, }; const res = new http.ServerResponse(req); const chunks = []; const resWrite = res.write; // @ts-ignore res.write = (chunk, encoding, callback) => { let encodingWasGiven = false; if (typeof encoding === 'string') { // assume this was called like this: // write(chunk, encoding[, callback]) encodingWasGiven = true; } else { // this was called like this: // write(chunk[, callback) callback = encoding; encoding = 'utf8'; } if (chunk instanceof Buffer) { chunks.push(chunk); } else { chunks.push(Buffer.from(chunk, encoding)); } if (encodingWasGiven) { // @ts-ignore resWrite.call(res, chunk, encoding, callback); } else { // @ts-ignore resWrite.call(res, chunk, callback); } }; res.getHeadersAsObject = () => { const headersString = res['_header']; const headers = {}; for (const kv of headersString.split('\r\n')) { const pos = kv.indexOf(':'); if (pos === -1) { continue; } const key = kv.slice(0, pos); const value = kv.slice(pos + 1).trim(); if (value == null || value === '') { continue; } headers[key] = value; } // Transfer-Encoding: chunked gets added automatically, but // this is not valid under AWS lambda delete headers['Transfer-Encoding']; return headers; }; res.getBodyAsBuffer = () => { return Buffer.concat(chunks); }; return { req, res, }; } export function apiGatewayResponseFromHttp(res) { var _a, _b, _c; const gatewayRes = res; const headers = (_a = gatewayRes.getHeadersAsObject) === null || _a === void 0 ? void 0 : _a.call(gatewayRes); const body = (_c = (_b = gatewayRes.getBodyAsBuffer) === null || _b === void 0 ? void 0 : _b.call(gatewayRes).toString('utf8')) !== null && _c !== void 0 ? _c : ''; const response = { statusCode: res.statusCode, headers, body, isBase64Encoded: false, }; return response; } //# sourceMappingURL=aws-lambda-adapters.js.map