UNPKG

somod-chat-service

Version:

Serverless Chat Service from SOMOD

68 lines (67 loc) 2.66 kB
import { DynamoDBClient, GetItemCommand, PutItemCommand, UpdateItemCommand } from "@aws-sdk/client-dynamodb"; import { convertToAttr, marshall, unmarshall } from "@aws-sdk/util-dynamodb"; import { RouteBuilder } from "somod-http-extension"; import { v1 as v1uuid } from "uuid"; const builder = new RouteBuilder(); const dynamodb = new DynamoDBClient(); const createThread = async (request) => { const now = Date.now(); const thread = { ...request.body, id: v1uuid().split("-").join(""), createdAt: now }; const putItemCommand = new PutItemCommand({ TableName: process.env.THREAD_TABLE_NAME + "", Item: marshall(thread), ConditionExpression: "attribute_not_exists(#id)", ExpressionAttributeNames: { "#id": "id" } }); await dynamodb.send(putItemCommand); return { statusCode: 200, headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify(thread) }; }; const getThread = async (request) => { const getItemCommand = new GetItemCommand({ TableName: process.env.THREAD_TABLE_NAME + "", Key: marshall({ id: request.parameters.path.id }) }); const result = await dynamodb.send(getItemCommand); return result.Item ? { statusCode: 200, headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify(unmarshall(result.Item)) } : { statusCode: 404 }; }; const updateSessionRequired = async (request) => { const updateItemCommand = new UpdateItemCommand({ TableName: process.env.THREAD_TABLE_NAME + "", Key: marshall({ id: request.parameters.path.id }), UpdateExpression: "SET #sessionRequired = :sessionRequired, #sessionRequiredTill = :sessionRequiredTill", ExpressionAttributeNames: { "#sessionRequired": "sessionRequired", "#sessionRequiredTill": "sessionRequiredTill" }, ExpressionAttributeValues: { ":sessionRequired": convertToAttr(request.body.sessionRequired), ":sessionRequiredTill": convertToAttr(request.body.sessionRequiredTill) } }); await dynamodb.send(updateItemCommand); return { statusCode: 200, headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify({ message: "Thread updated successfully" }) }; }; builder.add("/thread", "POST", createThread); builder.add("/thread/{id}", "GET", getThread); builder.add("/thread/{id}/session", "POST", updateSessionRequired); export default builder.getHandler();