Reputation: 11
validator.js
exports.bodyValidator = (schema) => ({
before: (handler, next) => {
const { body } = handler.event;
if (!body) {
throw new Error("Empty request body!");
}
const data = JSON.parse(body);
const { error } = schema.validate(data, { abortEarly: false });
if (error) {
const validationErrors = error.details.map(detail => detail.message);
throw new Error(`Validation failed: ${validationErrors.join(', ')}`);
} else {
next();
}
},
});
addTodo.js
"use strict"
const { v4 } = require("uuid")
const AWS = require("aws-sdk")
const middy = require("middy")
const Joi = require("joi")
const { errorHandler } = require("../utils/errorHandler")
const { bodyValidator } = require("../utils/validator")
const { authorize } = require("../utils/tokenValidator")
const todoSchema = Joi.object({
todo: Joi.string().required(),
priority: Joi.number().integer().min(1).max(5)
})
const addTodo = middy(async (event) => {
const dynamo = new AWS.DynamoDB.DocumentClient()
const { username: userEmail } = event.user
const { todo } = JSON.parse(event.body)
const { priority } = JSON.parse(event.body)
const createdAt = new Date().toISOString()
const id = v4()
console.log("This is the id:", id)
const newTodo = {
id,
userEmail,
todo,
priority,
createdAt,
completed: false
}
const params = {
TableName: process.env.TABLE_NAME,
Item: newTodo
}
console.log("Saving new todo:", newTodo);
await dynamo.put(params).promise()
console.log("New todo successfully saved:", newTodo);
return {
statusCode: 200,
body: JSON.stringify(newTodo),
};
}).use(authorize())
.use(bodyValidator(todoSchema))
.use(errorHandler());
module.exports = {
handler: addTodo
}
Hello guys, I have the following question: For some reason the function "addTodo" stores the item twice into the AWS DynamoDB table (in case of a successful validation). If the validation throws an error, one instance of the item still gets stored into the database (although it should not be stored in this case). Can someone find a reason for this weird behaviour?
Upvotes: 0
Views: 53