Created
November 1, 2022 09:51
-
-
Save cal0610/2c9500dd7fb5247d75d52dca3a7bfa2a to your computer and use it in GitHub Desktop.
create store
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'; | |
import { v4 as uuidv4 } from 'uuid'; | |
const TABLE_NAME = process.env.STORE_TABLE_NAME || ''; | |
const PRIMARY_KEY = process.env.STORE_PRIMARY_KEY || ''; | |
const db = new AWS.DynamoDB.DocumentClient(); | |
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.`; | |
export const handler = async (event: any = {}): Promise<any> => { | |
if (!event.body) { | |
return { | |
statusCode: 400, | |
body: 'invalid request, you are missing the parameter body' | |
}; | |
} | |
const item = typeof event.body == 'object' ? event.body : JSON.parse(event.body); | |
item[PRIMARY_KEY] = uuidv4(); | |
const params = { | |
TableName: TABLE_NAME, | |
Item: item | |
}; | |
try { | |
await db.put(params).promise(); | |
return { | |
statusCode: 201, | |
headers: { | |
'Access-Control-Allow-Origin': '*' | |
}, | |
body: JSON.stringify(item) | |
}; | |
} 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