Skip to content

Commit

Permalink
Merge branch 'new-master'
Browse files Browse the repository at this point in the history
  • Loading branch information
fwang committed Apr 9, 2020
2 parents d7df742 + 6b0e70e commit a0fd61d
Show file tree
Hide file tree
Showing 15 changed files with 10,990 additions and 3,875 deletions.
24 changes: 10 additions & 14 deletions billing.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import stripePackage from "stripe";
import handler from "./libs/handler-lib";
import { calculateCost } from "./libs/billing-lib";
import { success, failure } from "./libs/response-lib";

export async function main(event, context) {
export const main = handler(async (event, context) => {
const { storage, source } = JSON.parse(event.body);
const amount = calculateCost(storage);
const description = "Scratch charge";

// Load our secret key from the environment variables
const stripe = stripePackage(process.env.stripeSecretKey);

try {
await stripe.charges.create({
source,
amount,
description,
currency: "usd"
});
return success({ status: true });
} catch (e) {
return failure({ message: e.message });
}
}
await stripe.charges.create({
source,
amount,
description,
currency: "usd"
});
return { status: true };
});
27 changes: 16 additions & 11 deletions create.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import uuid from "uuid";
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
import * as uuid from "uuid";
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

export async function main(event, context) {
export const main = handler(async (event, context) => {
const data = JSON.parse(event.body);
const params = {
TableName: process.env.tableName,
// 'Item' contains the attributes of the item to be created
// - 'userId': user identities are federated through the
// Cognito Identity Pool, we will use the identity id
// as the user id of the authenticated user
// - 'noteId': a unique uuid
// - 'content': parsed from request body
// - 'attachment': parsed from request body
// - 'createdAt': current Unix timestamp
Item: {
userId: event.requestContext.identity.cognitoIdentityId,
noteId: uuid.v1(),
Expand All @@ -15,10 +23,7 @@ export async function main(event, context) {
}
};

try {
await dynamoDbLib.call("put", params);
return success(params.Item);
} catch (e) {
return failure({ status: false });
}
}
await dynamoDb.put(params);

return params.Item;
});
17 changes: 7 additions & 10 deletions delete.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

export async function main(event, context) {
export const main = handler(async (event, context) => {
const params = {
TableName: process.env.tableName,
// 'Key' defines the partition key and sort key of the item to be removed
Expand All @@ -13,10 +13,7 @@ export async function main(event, context) {
}
};

try {
await dynamoDbLib.call("delete", params);
return success({ status: true });
} catch (e) {
return failure({ status: false });
}
}
await dynamoDb.delete(params);

return { status: true };
});
24 changes: 10 additions & 14 deletions get.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

export async function main(event, context) {
export const main = handler(async (event, context) => {
const params = {
TableName: process.env.tableName,
// 'Key' defines the partition key and sort key of the item to be retrieved
Expand All @@ -13,15 +13,11 @@ export async function main(event, context) {
}
};

try {
const result = await dynamoDbLib.call("get", params);
if (result.Item) {
// Return the retrieved item
return success(result.Item);
} else {
return failure({ status: false, error: "Item not found." });
}
} catch (e) {
return failure({ status: false });
const result = await dynamoDb.get(params);
if ( ! result.Item) {
throw new Error("Item not found.");
}
}

// Return the retrieved item
return result.Item;
});
42 changes: 42 additions & 0 deletions libs/debug-lib.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import AWS from "aws-sdk";
import util from "util";

// Log AWS SDK calls
AWS.config.logger = { log: debug };

let logs;
let timeoutTimer;

export function init(event, context) {
logs = [];

// Log API event
debug("API event", {
body: event.body,
pathParameters: event.pathParameters,
queryStringParameters: event.queryStringParameters,
});

// Start timeout timer
timeoutTimer = setTimeout(() => {
timeoutTimer && flush(new Error("Lambda will timeout in 100 ms"));
}, context.getRemainingTimeInMillis() - 100);
}

export function end() {
// Clear timeout timer
clearTimeout(timeoutTimer);
timeoutTimer = null;
}

export function flush(e) {
logs.forEach(({ date, string }) => console.debug(date, string));
console.error(e);
}

export default function debug() {
logs.push({
date: new Date(),
string: util.format.apply(null, arguments),
});
}
12 changes: 8 additions & 4 deletions libs/dynamodb-lib.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import AWS from "aws-sdk";

export function call(action, params) {
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const client = new AWS.DynamoDB.DocumentClient();

return dynamoDb[action](params).promise();
}
export default {
get : (params) => client.get(params).promise(),
put : (params) => client.put(params).promise(),
query : (params) => client.query(params).promise(),
update: (params) => client.update(params).promise(),
delete: (params) => client.delete(params).promise(),
};
30 changes: 30 additions & 0 deletions libs/handler-lib.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as debug from "./debug-lib";

export default function handler(lambda) {
return function (event, context) {
return Promise.resolve()
// Start debugger
.then(() => debug.init(event, context))
// Run the Lambda
.then(() => lambda(event, context))
// On success
.then((responseBody) => [200, responseBody])
// On failure
.catch((e) => {
// Print debug messages
debug.flush(e);
return [500, { error: e.message }];
})
// Return HTTP response
.then(([statusCode, body]) => ({
statusCode,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify(body),
}))
// Cleanup debugger
.finally(debug.end);
};
}
19 changes: 8 additions & 11 deletions list.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

export async function main(event, context) {
export const main = handler(async (event, context) => {
const params = {
TableName: process.env.tableName,
// 'KeyConditionExpression' defines the condition for the query
Expand All @@ -16,11 +16,8 @@ export async function main(event, context) {
}
};

try {
const result = await dynamoDbLib.call("query", params);
// Return the matching list of items in response body
return success(result.Items);
} catch (e) {
return failure({ status: false });
}
}
const result = await dynamoDb.query(params);

// Return the matching list of items in response body
return result.Items;
});
2 changes: 1 addition & 1 deletion mocks/delete-event.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"pathParameters": {
"id": "578eb840-f70f-11e6-9d1a-1359b3b22944"
"id": "2b82e2c0-793f-11ea-9602-6d514f529482"
},
"requestContext": {
"identity": {
Expand Down
2 changes: 1 addition & 1 deletion mocks/get-event.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"pathParameters": {
"id": "578eb840-f70f-11e6-9d1a-1359b3b22944"
"id": "2b82e2c0-793f-11ea-9602-6d514f529482"
},
"requestContext": {
"identity": {
Expand Down
2 changes: 1 addition & 1 deletion mocks/update-event.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"body": "{\"content\":\"new world\",\"attachment\":\"new.jpg\"}",
"pathParameters": {
"id": "578eb840-f70f-11e6-9d1a-1359b3b22944"
"id": "2b82e2c0-793f-11ea-9602-6d514f529482"
},
"requestContext": {
"identity": {
Expand Down
Loading

0 comments on commit a0fd61d

Please sign in to comment.