Skip to content

Instantly share code, notes, and snippets.

@gcchaan
Last active May 11, 2023 02:02
Show Gist options
  • Save gcchaan/1969638229191b6eb69913b5f82f85e6 to your computer and use it in GitHub Desktop.
Save gcchaan/1969638229191b6eb69913b5f82f85e6 to your computer and use it in GitHub Desktop.
Local server for testing lambda-api
/**
* refs. https://github.com/jeremydaly/lambda-api/issues/53#issuecomment-450578262
*/
import { api } from "./src/app";
import {
APIGatewayProxyEventV2,
APIGatewayEventRequestContextV2,
APIGatewayProxyEventHeaders,
Context,
} from "aws-lambda";
import * as urlLib from "url";
import * as http from "http";
const serverWrapper: http.Server = http.createServer(
async (
request: http.IncomingMessage,
response: http.ServerResponse
): Promise<void> => {
if (!request.method) {
return;
}
const url = new urlLib.URL(
request.url || "",
`http://${request.headers.host}/`
);
let body = "";
request.on("data", (chunk) => {
body += chunk;
});
// The event object we're faking is a lightweight based on:
// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-api-gateway-request
const path = url.pathname;
const event: APIGatewayProxyEventV2 = {
version: "2.0",
routeKey: "ANY /nodejs-apig-function-1G3XMPLZXVXYI",
rawPath: path,
cookies: [
"s_fid=7AABXMPL1AFD9BBF-0643XMPL09956DE2",
"regStatus=pre-register",
],
rawQueryString: "",
queryStringParameters: Array.from(url.searchParams.keys()).reduce(
(output: Record<string, string>, key): Record<string, string> => {
output[key] = url.searchParams.get(key) || "";
return output;
},
{}
),
headers: request.headers as APIGatewayProxyEventHeaders,
requestContext: {
http: {
method: request.method.toUpperCase(),
path: path,
protocol: "HTTP/1.1",
sourceIp: "127.0.0.1",
userAgent: request.headers?.[`user-agent`] || "",
},
stage: "default",
} as APIGatewayEventRequestContextV2,
pathParameters: {},
stageVariables: {},
isBase64Encoded: false,
body: body,
};
console.log(event);
try {
const res = await api.run(event, {} as Context);
let { body, headers, statusCode } = res;
if (res.isBase64Encoded) {
body = Buffer.from(body, "base64");
}
if (!headers["content-length"] && body) {
headers["content-length"] = body.length;
}
response.writeHead(statusCode, headers);
response.end(body);
} catch (err) {
console.error("Something went horribly, horribly wrong");
console.error(err);
response.writeHead(500, { "content-length": 0 });
response.end("");
}
}
);
serverWrapper.listen(process.env.PORT || 3000, () => {
const address = serverWrapper.address();
if (address && typeof address === "object") {
console.log(`Listening on http://localhost:${address.port}/`);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment