This repository was archived by the owner on Jun 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 911
Expand file tree
/
Copy pathapp.js
More file actions
83 lines (72 loc) · 2.2 KB
/
app.js
File metadata and controls
83 lines (72 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
// default imports
const AWSXRay = require("aws-xray-sdk-core");
const AWS = AWSXRay.captureAWS(require("aws-sdk"));
const { metricScope, Unit } = require("aws-embedded-metrics");
const DDB = new AWS.DynamoDB({ apiVersion: "2012-10-08" });
// environment variables
const { TABLE_NAME, ENDPOINT_OVERRIDE, REGION } = process.env;
const options = { region: REGION };
AWS.config.update({ region: REGION });
if (ENDPOINT_OVERRIDE !== "") {
options.endpoint = ENDPOINT_OVERRIDE;
}
const docClient = new AWS.DynamoDB.DocumentClient(options);
// response helper
const response = (statusCode, body, additionalHeaders) => ({
statusCode,
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
...additionalHeaders,
},
});
function isValidRequest(event) {
return (
event !== null &&
event.pathParameters !== null &&
event.pathParameters.id !== null &&
/^[\w-]+$/.test(event.pathParameters.id)
);
}
function getCognitoUsername(event) {
let authHeader = event.requestContext.authorizer;
if (authHeader !== null) {
return authHeader.claims["cognito:username"];
}
return null;
}
function deleteRecordById(username, recordId) {
let params = {
TableName: TABLE_NAME,
Key: {
"cognito-username": username,
id: recordId,
},
};
return docClient.delete(params);
}
// Lambda Handler
exports.deleteToDoItem = metricScope((metrics) => async (event, context) => {
metrics.setNamespace("TodoApp");
metrics.putDimensions({ Service: "deleteTodo" });
metrics.setProperty("RequestId", context.requestId);
if (!isValidRequest(event)) {
metrics.putMetric("Error", 1, Unit.Count);
return response(400, { message: "Error: Invalid request" });
}
try {
let username = getCognitoUsername(event);
let data = await deleteRecordById(
username,
event.pathParameters.id
).promise();
metrics.putMetric("Success", 1, Unit.Count);
return response(200, data);
} catch (err) {
metrics.putMetric("Error", 1, Unit.Count);
return response(400, { message: err.message });
}
});