aboutsummaryrefslogtreecommitdiff
path: root/examples/lambda.ts
diff options
context:
space:
mode:
Diffstat (limited to 'examples/lambda.ts')
-rw-r--r--examples/lambda.ts214
1 files changed, 214 insertions, 0 deletions
diff --git a/examples/lambda.ts b/examples/lambda.ts
new file mode 100644
index 000000000..ab2d5bb2b
--- /dev/null
+++ b/examples/lambda.ts
@@ -0,0 +1,214 @@
+const { AWS_LAMBDA_RUNTIME_API, LAMBDA_TASK_ROOT, _HANDLER } = process.env;
+
+if (!AWS_LAMBDA_RUNTIME_API || AWS_LAMBDA_RUNTIME_API === "") {
+ throw new Error("AWS_LAMBDA_RUNTIME_API is not set");
+}
+
+const nextURL = `http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next`;
+const sourceDir = LAMBDA_TASK_ROOT;
+if (!sourceDir) {
+ throw new Error("handler is not set");
+}
+
+// don't care if this fails
+if (process.cwd() !== sourceDir) {
+ try {
+ process.chdir(sourceDir);
+ } catch (e) {}
+}
+
+var handlerDot = _HANDLER.lastIndexOf(".");
+var sourcefile = handlerDot > 0 ? _HANDLER.substring(0, handlerDot) : _HANDLER;
+if (sourcefile.length === 0) {
+ throw new Error("handler is not set");
+}
+if (!sourcefile.startsWith("/")) {
+ sourcefile = `./${sourcefile}`;
+}
+function noop() {}
+const method = (handlerDot > 0 ? _HANDLER.substring(handlerDot) : "") || "GET";
+
+if (typeof process.env.VERBOSE !== "undefined") {
+ console.time(`Loaded ${sourcefile}`);
+}
+var Handler;
+
+try {
+ Handler = await import(sourcefile);
+} catch (e) {
+ console.error("Error loading sourcefile:", e);
+ try {
+ await fetch(
+ new URL(`http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/init/error`)
+ .href,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ errorMessage: e.message,
+ errorType: e.name,
+ stackTrace: e?.stack?.split("\n") ?? [],
+ }),
+ }
+ );
+ } catch (e2) {
+ console.error("Error sending error to runtime:", e2);
+ }
+ process.exit(1);
+}
+
+if (typeof process.env.VERBOSE !== "undefined") {
+ console.timeEnd(`Loaded ${sourcefile}`);
+}
+
+const handlerFunction = Handler.default?.fetch;
+if (typeof handlerFunction !== "function") {
+ const e = new Error(`${sourcefile} must export default a function called fetch
+
+Here is an example:
+
+export default {
+ fetch(req) {
+ return new Response("Hello World");
+ }
+}
+`);
+
+ console.error(e);
+
+ try {
+ await fetch(
+ new URL(`http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/init/error`)
+ .href,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ errorMessage: e.message,
+ errorType: e.name,
+ stackTrace: e?.stack?.split("\n") ?? [],
+ }),
+ }
+ );
+ } catch (e2) {
+ console.error("Error sending error to runtime:", e2);
+ }
+
+ process.exit(1);
+}
+
+var baseURLString = AWS_LAMBDA_RUNTIME_API;
+if ("baseURI" in Handler.default) {
+ baseURLString = Handler.default.baseURI?.toString();
+}
+
+var baseURL;
+try {
+ baseURL = new URL(baseURLString);
+} catch (e) {
+ console.error("Error parsing baseURI:", e);
+ try {
+ await fetch(
+ new URL(`http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/init/error`)
+ .href,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ errorMessage: e.message,
+ errorType: e.name,
+ stackTrace: e?.stack?.split("\n") || [],
+ }),
+ }
+ );
+ } catch (e2) {
+ console.error("Error sending error to runtime:", e2);
+ }
+
+ process.exit(1);
+}
+
+async function runHandler(response: Response) {
+ const traceID = response.headers.get("Lambda-Runtime-Trace-Id");
+ const requestID = response.headers.get("Lambda-Runtime-Aws-Request-Id");
+ var request = new Request(baseURL.href, {
+ method,
+ headers: response.headers,
+ body:
+ parseInt(response.headers.get("Content-Length") || "0", 10) > 0
+ ? await response.blob()
+ : undefined,
+ });
+ // we are done with the Response object here
+ // allow it to be GC'd
+ response = undefined;
+
+ var result: Response;
+ try {
+ if (typeof process.env.VERBOSE !== "undefined") {
+ console.time(`[${traceID}] Run ${request.url}`);
+ }
+ result = handlerFunction(request, {});
+ if (result && result.then) {
+ await result;
+ }
+ } catch (e1) {
+ if (typeof process.env.VERBOSE !== "undefined") {
+ console.error(`[${traceID}] Error running handler:`, e1);
+ }
+ fetch(
+ `http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/${requestID}/error`,
+ {
+ method: "POST",
+
+ body: JSON.stringify({
+ errorMessage: e1.message,
+ errorType: e1.name,
+ stackTrace: e1?.stack?.split("\n") ?? [],
+ }),
+ }
+ ).finally(noop);
+ return;
+ } finally {
+ if (typeof process.env.VERBOSE !== "undefined") {
+ console.timeEnd(`[${traceID}] Run ${request.url}`);
+ }
+ }
+
+ if (!result || !("headers" in result)) {
+ await fetch(
+ `http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/${requestID}/error`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ errorMessage: "Expected Response object",
+ errorType: "ExpectedResponseObject",
+ stackTrace: [],
+ }),
+ }
+ );
+ return;
+ }
+
+ await fetch(
+ `http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/${requestID}/response`,
+ {
+ method: "POST",
+ headers: result.headers,
+ body: await result.blob(),
+ }
+ );
+ result = undefined;
+}
+
+while (true) {
+ fetch(nextURL).then(runHandler, console.error);
+}
+
+export {};
/test/js/node/module/node-module-module.test.js?h=dave/assert-double-is-valid&id=365fc0d39ddfaed8683eb6ee75013a0fe3adcae2&follow=1'>implement `Module.prototype._compile` (#5840)Gravatar dave caruso 4-2/+78 2023-09-20feat(runtime): implement `console._stdout` (#5842)Gravatar dave caruso 2-1/+59 2023-09-20Improve types for `test.each`, `describe.each` (#5838)Gravatar Colin McDonnell 2-10/+59 2023-09-20Fix rendering of bun.lockb in vscode extensionGravatar Ashcon Partovi 5-114/+4 2023-09-20Run bun fmtGravatar Ashcon Partovi 2-12/+9 2023-09-20Update quickstartGravatar Colin McDonnell 1-0/+19 2023-09-20Update prisma guideGravatar Colin McDonnell 1-0/+6 2023-09-20Update env docGravatar Colin McDonnell 1-1/+1 2023-09-20Clarify hot modeGravatar Colin McDonnell 1-10/+9 2023-09-20[bun install] Add `-E` as alias of `--exact` (#5104)Gravatar Jonah Snider 2-2/+57 2023-09-20feat: switch disableTelemetry to bunfig (#5690)Gravatar Lucas Coratger 3-1/+14 2023-09-20Treat `undefined` value as empty in expect.toThrow (#5788)Gravatar LongYinan 1-3/+3 2023-09-20Fix various bugs in vscode extension (#5772)Gravatar JeremyFunk 3-9/+85 2023-09-20add `emitDecoratorMetadata` (#5777)Gravatar Dylan Conway 19-110/+1884 2023-09-20fix(doc): correct `server.reload` (#5799)Gravatar Ai Hoshino 1-1/+1 2023-09-20Call `Error.prepareStackTrace` on `new Error().stack` (#5802)Gravatar Jarred Sumner 6-155/+277 2023-09-20Fixes #5800Gravatar Jarred Sumner 1-1/+1 2023-09-20Fix path used in bunx (#5785)Gravatar Jarred Sumner 2-26/+51 2023-09-20Fix RedirectURLTooLong errors (#5786)Gravatar ggobbe 1-1/+1 2023-09-19Show when a newer version is available in the install screen (#5780)Gravatar Jarred Sumner 3-14/+95 2023-09-19Fix broken linksGravatar Colin McDonnell 4-4/+4