Go to file
2024-02-15 20:34:18 +01:00
README.md Initial commit 2024-02-15 20:34:18 +01:00
test.py Initial commit 2024-02-15 20:34:18 +01:00

REST API na środoiwsku AWS Lambda i DynamoDB

Konfiguracja

Poradnik jak skonfigurować środowisko można znaleźć pod adresem: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-dynamo-db.html

Kod

Poniżej znajduje się kod funkcji Lambda, która obsługuje zapytania HTTP i komunikuje się z bazą danych DynamoDB - wykonany na potrzebę zadania z przedmiotu Chmury obliczeniowe (zad. 6.2)

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
  DynamoDBDocumentClient,
  PutCommand,
  GetCommand,
  DeleteCommand,
} from "@aws-sdk/lib-dynamodb";
import { randomUUID } from 'crypto';

const client = new DynamoDBClient({});
const dynamo = DynamoDBDocumentClient.from(client);
const tableName = "posts";

const DB = {
  async create({ userId, title, body }) {
    const id = randomUUID();
    await dynamo.send(
      new PutCommand({
        TableName: tableName,
        Item: { id, userId, title, body },
      })
    );
    return await DB.get(id);
  },
  async get(id) {
    return (await dynamo.send(
      new GetCommand({
        TableName: tableName,
        Key: { id },
      })
    ))?.Item;
  },
  async update(id, { userId, title, body }) {
    await dynamo.send(
      new PutCommand({
        TableName: tableName,
        Item: { id, userId, title, body },
      })
    );
    return await DB.get(id);
  },
  async delete(id) {
    _result = await DB.get(id);
    await dynamo.send(
      new DeleteCommand({
        TableName: tableName,
        Key: { id },
      })
    );
    return _result;
  },
}

export const handler = async (event, context) => {
  let body;

  try {
    switch (event.routeKey) {
      case "POST /":
        body = await DB.create(JSON.parse(event.body));
        break;
      case "DELETE /{id}":
        body = await DB.delete(event.pathParameters.id);
        break;
      case "GET /{id}":
        body = await DB.get(event.pathParameters.id);
        break;
      case "PUT /{id}":
        body = await DB.update(event.pathParameters.id, JSON.parse(event.body));
        break;
      default:
        throw new Error(`Unsupported route: "${event.routeKey}"`);
    }

    return {
      statusCode: 200,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    };
  } catch (err) {
    return {
      statusCode: 400,
      body: JSON.stringify(err.message),
    };
  }
};