Skip to content

Instantly share code, notes, and snippets.

@BenSeward
Last active May 2, 2020 10:19
Show Gist options
  • Save BenSeward/3e321e9fab7b66149fa80df54c83cdc1 to your computer and use it in GitHub Desktop.
Save BenSeward/3e321e9fab7b66149fa80df54c83cdc1 to your computer and use it in GitHub Desktop.
provider:
name: aws
runtime: nodejs12.x
environment:
USER_TABLE: ${self:service}-${opt-stage, self:provider.stage}
USER_EMAIL_TABLE: "user-email-${opt:stage, self:provider.stage}"
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
Resource: "*"
resources:
Resources:
UsersDynamoDbTable:
Type: "AWS::DynamoDB::Table"
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
- AttributeName: "id"
AttributeType: "S"
KeySchema:
- AttributeName: "id"
KeyType: "HASH"
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
StreamSpecification:
StreamViewType: "NEW_AND_OLD_IMAGES"
TableName: ${self:provider.environment.USER_TABLE}
functions:
createUser:
handler: user.create
memorySize: 128
description: Creation of a new user account
events:
- http:
path: users
method: post
'use strict';
const uuid = require('uuid');
const AWS = require('aws-sdk');
AWS.config.setPromisesDependency(require('bluebird'));
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.create = async (event, context, callback) => {
const requestBody = JSON.parse(event.body);
const fullname = requestBody.fullname;
const email = requestBody.email;
if (typeof fullname !== 'string' || typeof email !== 'string') {
console.error('Validation Failed');
callback(new Error('Couldn\'t submit candidate because of validation errors.'));
return;
}
submitCandidateP(candidateInfo(fullname, email))
.then(res => {
callback(null, {
statusCode: 200,
body: JSON.stringify({
message: `Sucessfully submitted candidate with email ${email}`,
candidateId: res.id
})
});
})
.catch(err => {
console.log(err);
callback(null, {
statusCode: 500,
body: JSON.stringify({
message: `Unable to submit candidate with email ${email}`
})
})
});
};
const submitCandidateP = candidate => {
console.log('Submitting candidate to:', process.env.USER_TABLE);
const candidateInfo = {
TableName: process.env.USER_TABLE,
Item: candidate,
};
console.log(candidateInfo);
return dynamoDb.put(candidateInfo).promise()
.catch(err => console.log(err))
.then(res => candidate);
};
const candidateInfo = (fullname, email) => {
const timestamp = new Date().getTime();
return {
id: uuid.v1(),
fullname: fullname,
email: email,
submittedAt: timestamp,
updatedAt: timestamp,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment