Skip to content

05 API Gateway

JP Barbosa edited this page Sep 18, 2022 · 9 revisions

API Gateway

Diagram

API Gateway

Create API Gateway

code ./stacks/resources/api.ts
import { Api, Stack, Table } from "@serverless-stack/resources";

type CreateApiOptions = { table: Table };

type CreateApi = (stack: Stack, options: CreateApiOptions) => Api;

export const createApi: CreateApi = (stack, { table }) => {
  const api = new Api(stack, "api", {
    defaults: {
      function: {
        environment: {
          table: table.tableName,
        },
      },
    },
    routes: {
      "GET /": "functions/results.handler",
    },
  });

  api.attachPermissions([table]);

  return api;
};

Update resources index

code ./stacks/resources/index.ts
export * from "./api";
export * from "./bucket";
export * from "./bus";
export * from "./queue";
export * from "./table";

Update stack

code ./stacks/MyStack.ts
import { StackContext } from "@serverless-stack/resources";
import {
  createBucket,
  createTable,
  createQueue,
  createBus,
  createApi,
} from "./resources";

export function MyStack({ stack }: StackContext) {
  const bucket = createBucket(stack);
  const table = createTable(stack);
  const queue = createQueue(stack, { bucket, table });
  const bus = createBus(stack, { bucket, queue });
  const api = createApi(stack, { table });

  stack.addOutputs({
    ApiEndpoint: api.url,
  });
}

Create results handler

code ./services/functions/results.ts
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
import { DynamoDB } from "aws-sdk";

const dynamoDb = new DynamoDB.DocumentClient();

export const handler = async (event: APIGatewayProxyHandlerV2) => {
  const params = {
    TableName: String(process.env.table),
  };

  try {
    const result = await dynamoDb.scan(params).promise();

    const sortedResult = {
      ...result,
      Items: result.Items?.sort((a, b) => {
        return b.createdAt - a.createdAt;
      }),
    };

    return {
      statusCode: 200,
      body: JSON.stringify(sortedResult),
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify(error),
    };
  }
};

Preview

image
Clone this wiki locally