Created
November 1, 2022 09:58
-
-
Save cal0610/357b8ffe42e44441d3e7bc1e95f85534 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as AWS from 'aws-sdk'; | |
const TABLE_NAME = process.env.STORE_TABLE_NAME || ''; | |
const PRIMARY_KEY = process.env.STORE_PRIMARY_KEY || ''; | |
const RESERVED_RESPONSE = `Error: You're using AWS reserved keywords as attributes`, | |
DYNAMODB_EXECUTION_ERROR = `Error: Execution update, caused a Dynamodb error, please take a look at your CloudWatch Logs.`; | |
const db = new AWS.DynamoDB.DocumentClient(); | |
export const handler = async (event: any = {}): Promise<any> => { | |
if (!event.body) { | |
return { | |
statusCode: 400, | |
body: 'invalid request, you are missing the parameter body', | |
}; | |
} | |
const editedItemId = event.pathParameters.id; | |
if (!editedItemId) { | |
return { | |
statusCode: 400, | |
body: 'invalid request, you are missing the path parameter id', | |
}; | |
} | |
const editedItem: any = | |
typeof event.body == 'object' ? event.body : JSON.parse(event.body); | |
const editedItemProperties = Object.keys(editedItem); | |
if (!editedItem || editedItemProperties.length < 1) { | |
return { statusCode: 400, body: 'invalid request, no arguments provided' }; | |
} | |
const firstProperty = editedItemProperties.splice(0, 1); | |
const params: any = { | |
TableName: TABLE_NAME, | |
Key: { | |
[PRIMARY_KEY]: editedItemId, | |
}, | |
UpdateExpression: `set ${firstProperty} = :${firstProperty}`, | |
ExpressionAttributeValues: {}, | |
ReturnValues: 'UPDATED_NEW', | |
}; | |
params.ExpressionAttributeValues[`:${firstProperty}`] = | |
editedItem[`${firstProperty}`]; | |
editedItemProperties.forEach((property) => { | |
params.UpdateExpression += `, ${property} = :${property}`; | |
params.ExpressionAttributeValues[`:${property}`] = editedItem[property]; | |
}); | |
try { | |
await db.update(params).promise(); | |
return { | |
statusCode: 204, | |
headers: { | |
'Access-Control-Allow-Origin': '*', | |
}, | |
body: '', | |
}; | |
} catch (dbError: any) { | |
const errorResponse = | |
dbError.code === 'ValidationException' && | |
dbError.message.includes('reserved keyword') | |
? DYNAMODB_EXECUTION_ERROR | |
: RESERVED_RESPONSE; | |
return { statusCode: 500, body: errorResponse }; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment