Skip to content

Commit

Permalink
Adding our Serverless API
Browse files Browse the repository at this point in the history
  • Loading branch information
fwang committed Apr 8, 2020
1 parent 1619d18 commit 08789dc
Show file tree
Hide file tree
Showing 22 changed files with 9,861 additions and 4,170 deletions.
20 changes: 20 additions & 0 deletions billing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import stripePackage from "stripe";
import handler from "./libs/handler-lib";
import { calculateCost } from "./libs/billing-lib";

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);

await stripe.charges.create({
source,
amount,
description,
currency: "usd"
});
return { status: true };
});
29 changes: 29 additions & 0 deletions create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as uuid from "uuid";
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

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(),
content: data.content,
attachment: data.attachment,
createdAt: Date.now()
}
};

await dynamoDb.put(params);

return params.Item;
});
19 changes: 19 additions & 0 deletions delete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

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
// - 'userId': Identity Pool identity id of the authenticated user
// - 'noteId': path parameter
Key: {
userId: event.requestContext.identity.cognitoIdentityId,
noteId: event.pathParameters.id
}
};

await dynamoDb.delete(params);

return { status: true };
});
8 changes: 0 additions & 8 deletions env.example

This file was deleted.

23 changes: 23 additions & 0 deletions get.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

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
// - 'userId': Identity Pool identity id of the authenticated user
// - 'noteId': path parameter
Key: {
userId: event.requestContext.identity.cognitoIdentityId,
noteId: event.pathParameters.id
}
};

const result = await dynamoDb.get(params);
if ( ! result.Item) {
throw new Error("Item not found.");
}

// Return the retrieved item
return result.Item;
});
9 changes: 9 additions & 0 deletions libs/billing-lib.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function calculateCost(storage) {
const rate = storage <= 10
? 4
: storage <= 100
? 2
: 1;

return rate * storage * 100;
}
11 changes: 11 additions & 0 deletions libs/dynamodb-lib.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import AWS from "aws-sdk";

const client = new AWS.DynamoDB.DocumentClient();

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(),
};
22 changes: 22 additions & 0 deletions libs/handler-lib.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export default function handler(lambda) {
return function (event, context) {
return Promise.resolve()
// Run the Lambda
.then(() => lambda(event, context))
// On success
.then((responseBody) => [200, responseBody])
// On failure
.catch((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),
}));
};
}
23 changes: 23 additions & 0 deletions list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

export const main = handler(async (event, context) => {
const params = {
TableName: process.env.tableName,
// 'KeyConditionExpression' defines the condition for the query
// - 'userId = :userId': only return items with matching 'userId'
// partition key
// 'ExpressionAttributeValues' defines the value in the condition
// - ':userId': defines 'userId' to be Identity Pool identity id
// of the authenticated user
KeyConditionExpression: "userId = :userId",
ExpressionAttributeValues: {
":userId": event.requestContext.identity.cognitoIdentityId
}
};

const result = await dynamoDb.query(params);

// Return the matching list of items in response body
return result.Items;
});
8 changes: 8 additions & 0 deletions mocks/billing-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"body": "{\"source\":\"tok_visa\",\"storage\":21}",
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"
}
}
}
8 changes: 8 additions & 0 deletions mocks/create-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"body": "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}",
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"
}
}
}
10 changes: 10 additions & 0 deletions mocks/delete-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"pathParameters": {
"id": "2b82e2c0-793f-11ea-9602-6d514f529482"
},
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"
}
}
}
10 changes: 10 additions & 0 deletions mocks/get-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"pathParameters": {
"id": "2b82e2c0-793f-11ea-9602-6d514f529482"
},
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"
}
}
}
7 changes: 7 additions & 0 deletions mocks/list-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"
}
}
}
11 changes: 11 additions & 0 deletions mocks/update-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"body": "{\"content\":\"new world\",\"attachment\":\"new.jpg\"}",
"pathParameters": {
"id": "2b82e2c0-793f-11ea-9602-6d514f529482"
},
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"
}
}
}
Loading

0 comments on commit 08789dc

Please sign in to comment.