somod-chat-service
Version:
Serverless Chat Service from SOMOD
59 lines (58 loc) • 2.24 kB
JavaScript
import { marshall } from "@aws-sdk/util-dynamodb";
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";
import { threadCache } from "./threadCache";
const dynamodb = new DynamoDBClient();
const msgTTL = parseInt(process.env.CHAT_MESSAGE_TTL ?? "7776000", 10); // 3 months in seconds
export const getMessageTTL = (now) => {
const _now = now ?? Date.now();
const __now = Math.floor(_now / 1000);
return __now + msgTTL;
};
export const putMessage = async (tableName, userId, message) => {
const msg = {
...message,
seqNo: Date.now()
};
const messageWithKeys = {
...msg,
userId,
expiresAt: getMessageTTL()
};
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, typeToAllowedActionsMap) => {
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]) {
errorMessage = `Invalid type : type must be one of (${typeToAllowedActionsMap[message.type].join(", ")})`;
}
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
})
};
}
};