From 4fa83558bed824d95c54b6b13dc7b7c78788b4e3 Mon Sep 17 00:00:00 2001 From: pozeus Date: Wed, 26 Aug 2020 13:49:24 +0200 Subject: [PATCH] Create update.ts --- .../todos/update.ts | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 aws-node-typescript-rest-api-with-dynamodb/todos/update.ts diff --git a/aws-node-typescript-rest-api-with-dynamodb/todos/update.ts b/aws-node-typescript-rest-api-with-dynamodb/todos/update.ts new file mode 100644 index 000000000..c852c6202 --- /dev/null +++ b/aws-node-typescript-rest-api-with-dynamodb/todos/update.ts @@ -0,0 +1,59 @@ +'use strict'; + +const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies + +const dynamoDb = new AWS.DynamoDB.DocumentClient(); + +module.exports.update = (event, context, callback) => { + const timestamp = new Date().getTime(); + const data = JSON.parse(event.body); + + // validation + if (typeof data.text !== 'string' || typeof data.checked !== 'boolean') { + console.error('Validation Failed'); + callback(null, { + statusCode: 400, + headers: { 'Content-Type': 'text/plain' }, + body: 'Couldn\'t update the todo item.', + }); + return; + } + + const params = { + TableName: process.env.DYNAMODB_TABLE, + Key: { + id: event.pathParameters.id, + }, + ExpressionAttributeNames: { + '#todo_text': 'text', + }, + ExpressionAttributeValues: { + ':text': data.text, + ':checked': data.checked, + ':updatedAt': timestamp, + }, + UpdateExpression: 'SET #todo_text = :text, checked = :checked, updatedAt = :updatedAt', + ReturnValues: 'ALL_NEW', + }; + + // update the todo in the database + dynamoDb.update(params, (error, result) => { + // handle potential errors + if (error) { + console.error(error); + callback(null, { + statusCode: error.statusCode || 501, + headers: { 'Content-Type': 'text/plain' }, + body: 'Couldn\'t fetch the todo item.', + }); + return; + } + + // create a response + const response = { + statusCode: 200, + body: JSON.stringify(result.Attributes), + }; + callback(null, response); + }); +};