Sikau

AWS · Day 3 · about 40 min

Lambda functions

Serverless handlers: API Gateway events in, status codes out.

Code without servers

With Lambda, you upload a function and AWS runs it on demand — zero to thousands of copies — and bills by the millisecond. API Gateway turns each HTTP request into an event object; your handler returns { statusCode, headers, body }. No servers to patch, but each request must stand alone.

A tiny router

const json = (statusCode, data) => ({ statusCode, headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });

function createHandler(routes) {
  const table = Object.entries(routes).map(([route, fn]) => {
    const [method, path] = route.split(" ");
    const names = [];
    const pattern = new RegExp(`^${path.replace(/\{(\w+)\}/g, (_, name) => (names.push(name), "([^/]+)"))}$`);
    return { method, pattern, names, fn };
  });
  return async (event) => {
    for (const { method, pattern, names, fn } of table) {
      const m = event.path.match(pattern);
      if (!m || method !== event.httpMethod) continue;
      let body = null;
      try {
        body = event.body ? JSON.parse(event.body) : null;
      } catch {
        return json(400, { error: "Invalid JSON" });
      }
      const params = Object.fromEntries(names.map((n, i) => [n, decodeURIComponent(m[i + 1])]));
      try {
        const [status, data] = await fn({ params, body, query: event.queryStringParameters ?? {}, event });
        return json(status, data);
      } catch {
        return json(500, { error: "Internal error" }); // never leak stack traces
      }
    }
    return json(404, { error: "Not found" });
  };
}

The rest of this lesson

  • The event and the responseexplain
  • Cold starts and stateexplain
  • Event to responsematch
  • Where should it live?match
  • Route eventswrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 8 lessons of AWS