Skip to content
This repository was archived by the owner on Jun 26, 2024. It is now read-only.

chore(todo-src): code cleanup and prettier formatting #48

Merged
merged 2 commits into from
May 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 74 additions & 73 deletions todo-src/addTodo/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,92 +2,93 @@
// 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" })
const { v1: uuidv1 } = require('uuid');
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" });
const { v1: uuidv1 } = require("uuid");

// environment variables
const { TABLE_NAME, ENDPOINT_OVERRIDE, REGION } = process.env
const options = { region: REGION }
AWS.config.update({ region: REGION })
const { TABLE_NAME, ENDPOINT_OVERRIDE, REGION } = process.env;
const options = { region: REGION };
AWS.config.update({ region: REGION });

if (ENDPOINT_OVERRIDE !== "") {
options.endpoint = ENDPOINT_OVERRIDE
options.endpoint = ENDPOINT_OVERRIDE;
}

const docClient = new AWS.DynamoDB.DocumentClient(options)
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(context, event) {
return (event.body !== null)
statusCode,
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
...additionalHeaders,
},
});

function isValidRequest(event) {
return event.body !== null;
}

function getCognitoUsername(event){
let authHeader = event.requestContext.authorizer;
if (authHeader !== null)
{
return authHeader.claims["cognito:username"];
}
return null;

function getCognitoUsername(event) {
let authHeader = event.requestContext.authorizer;
if (authHeader !== null) {
return authHeader.claims["cognito:username"];
}
return null;
}

function addRecord(event) {

let usernameField = {
"cognito-username": getCognitoUsername(event)
}

// auto generated date fields
let d = new Date()
let dISO = d.toISOString()
let auto_fields = {
"id": uuidv1(),
"creation_date": dISO,
"lastupdate_date": dISO
}

//merge the json objects
let item_body = {...usernameField, ...auto_fields, ...JSON.parse(event.body) }

console.log(item_body);

//final params to DynamoDB
const params = {
TableName: TABLE_NAME,
Item: item_body
}

return docClient.put(params)
let usernameField = {
"cognito-username": getCognitoUsername(event),
};

// auto generated date fields
let dISO = new Date().toISOString();
let auto_fields = {
id: uuidv1(),
creation_date: dISO,
lastupdate_date: dISO,
};

//merge the json objects
let item_body = {
...usernameField,
...auto_fields,
...JSON.parse(event.body),
};

console.log(item_body);

//final params to DynamoDB
const params = {
TableName: TABLE_NAME,
Item: item_body,
};

return docClient.put(params);
}

// Lambda Handler
exports.addToDoItem =
metricScope(metrics =>
async (event, context, callback) => {
metrics.setNamespace('TodoApp')
metrics.putDimensions({ Service: "addTodo" })
metrics.setProperty("RequestId", context.requestId)

if (!isValidRequest(context, event)) {
metrics.putMetric("Error", 1, Unit.Count)
return response(400, { message: "Error: Invalid request" })
}

try {
let data = await addRecord(event).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 })
}
}
)
exports.addToDoItem = metricScope((metrics) => async (event, context) => {
metrics.setNamespace("TodoApp");
metrics.putDimensions({ Service: "addTodo" });
metrics.setProperty("RequestId", context.requestId);

if (!isValidRequest(context, event)) {
metrics.putMetric("Error", 1, Unit.Count);
return response(400, { message: "Error: Invalid request" });
}

try {
let data = await addRecord(event).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 });
}
});
118 changes: 59 additions & 59 deletions todo-src/completeTodo/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,81 +2,81 @@
// 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" })
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 })
const { TABLE_NAME, ENDPOINT_OVERRIDE, REGION } = process.env;
const options = { region: REGION };
AWS.config.update({ region: REGION });

if (ENDPOINT_OVERRIDE !== "") {
options.endpoint = ENDPOINT_OVERRIDE
options.endpoint = ENDPOINT_OVERRIDE;
}

const docClient = new AWS.DynamoDB.DocumentClient(options)
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 },
})
statusCode,
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
...additionalHeaders,
},
});

function isValidRequest(context, event) {
return (event !== null) &&
(event.pathParameters !== null) &&
(event.pathParameters.id !== null) &&
(/^[\w-]+$/.test(event.pathParameters.id))
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 getCognitoUsername(event) {
let authHeader = event.requestContext.authorizer;
if (authHeader !== null) {
return authHeader.claims["cognito:username"];
}
return null;
}

function updateRecord(username, recordId) {
let params = {
TableName: TABLE_NAME,
Key: {
"cognito-username": username,
"id": recordId
},
UpdateExpression: "set #field = :value",
ExpressionAttributeNames: { '#field': 'completed' },
ExpressionAttributeValues: { ':value': true }
}
return docClient.update(params)
let params = {
TableName: TABLE_NAME,
Key: {
"cognito-username": username,
id: recordId,
},
UpdateExpression: "set #field = :value",
ExpressionAttributeNames: { "#field": "completed" },
ExpressionAttributeValues: { ":value": true },
};
return docClient.update(params);
}

// Lambda Handler
exports.completeToDoItem =
metricScope(metrics =>
async (event, context, callback) => {
metrics.setNamespace('TodoApp')
metrics.putDimensions({ Service: "completeTodo" })
metrics.setProperty("RequestId", context.requestId)

if (!isValidRequest(context, event)) {
metrics.putMetric("Error", 1, Unit.Count)
return response(400, { message: "Error: Invalid request" })
}
exports.completeToDoItem = metricScope((metrics) => async (event, context) => {
metrics.setNamespace("TodoApp");
metrics.putDimensions({ Service: "completeTodo" });
metrics.setProperty("RequestId", context.requestId);

try {
let username = getCognitoUsername(event);
let data = await updateRecord(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 })
}
}
)
if (!isValidRequest(context, event)) {
metrics.putMetric("Error", 1, Unit.Count);
return response(400, { message: "Error: Invalid request" });
}

try {
let username = getCognitoUsername(event);
let data = await updateRecord(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 });
}
});
Loading