UNPKG

somod-chat-service

Version:

Serverless Chat Service from SOMOD

47 lines (46 loc) 1.79 kB
import { marshall } from "@aws-sdk/util-dynamodb"; import { typeToAllowedActionsMap } from "./types"; import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb"; import { threadCache } from "./threadCache"; const dynamodb = new DynamoDBClient(); export const putMessage = async (tableName, userId, message) => { const msg = { ...message, seqNo: Date.now() }; const messageWithKeys = { ...msg, userId }; const putItemCommand = new PutItemCommand({ TableName: tableName, Item: marshall(messageWithKeys), ConditionExpression: "attribute_not_exists(#userId) AND attribute_not_exists(#seqNo)", ExpressionAttributeNames: { "#userId": "userId", "#seqNo": "seqNo" } }); await dynamodb.send(putItemCommand); return msg; }; export const validateIncomingMessage = async (message, userId) => { let errorMessage = undefined; const thread = await threadCache.get(message.threadId); if (thread === undefined) { errorMessage = "Invalid threadId : does not exist"; } else if (!thread.participants.includes(userId)) { errorMessage = `Invalid threadId : from '${userId}' is not a participant in thread '${thread.id}'`; } else if (!typeToAllowedActionsMap[message.type].includes(message.action)) { errorMessage = `Invalid action : action must be '${typeToAllowedActionsMap[message.type].join(",")}' for '${message.type}' type`; } if (errorMessage) { return { statusCode: 400, headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify({ message: errorMessage, threadId: message.threadId }) }; } };