AWS Lambda — serverless compute that runs code without servers.
1// handler.js2exports.handler = async (event) => {3 const { httpMethod, path, body } = event;45 if (httpMethod === "GET" && path === "/users") {6 const users = await db.query("SELECT * FROM users");7 return {8 statusCode: 200,9 headers: { "Content-Type": "application/json" },10 body: JSON.stringify({ data: users }),11 };12 }1314 if (httpMethod === "POST" && path === "/users") {15 const data = JSON.parse(body);16 const user = await db.insert("users", data);17 return {18 statusCode: 201,19 body: JSON.stringify({ data: user }),20 };21 }2223 return { statusCode: 404, body: "Not found" };24};2526// DB connection outside handler (reused)27const db = require("./db");
Serverless Framework:
1# serverless.yml2functions:3 api:4 handler: handler.handler5 events:6 - http:7 path: /{proxy+}8 method: ANY
Key points: