Skip to content

Instantly share code, notes, and snippets.

@artoliukkonen
Last active December 2, 2018 21:55
Show Gist options
  • Save artoliukkonen/de185923bac57dc0fa7483ad51f025ce to your computer and use it in GitHub Desktop.
Save artoliukkonen/de185923bac57dc0fa7483ad51f025ce to your computer and use it in GitHub Desktop.
Serverless blog workshop snippets
# DynamoDB Blog table for workshop
BlogTable:
Type: AWS::DynamoDB::Table
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:provider.environment.TABLE_NAME}
const AWS = require('aws-sdk');
const config = {
region: AWS.config.region || process.env.SERVERLESS_REGION || 'eu-west-1',
};
const dynamodb = new AWS.DynamoDB.DocumentClient(config);
class BlogStorage {
constructor() {
this.dynamodb = dynamodb;
this.baseParams = {
TableName: process.env.TABLE_NAME,
};
}
// Get all posts
// @see: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property
getPosts() {
const params = Object.assign({}, this.baseParams, {
AttributesToGet: [
'id',
'title',
'content',
'date',
],
});
return this.dynamodb.scan(params).promise();
}
// Add new post
// @see: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
savePost(post) {
const date = Date.now();
const id = date.toString();
const payload = Object.assign({}, post, { id, date });
const params = Object.assign({}, this.baseParams, { Item: payload });
return this.dynamodb.put(params).promise()
.then(() => ({ post: payload }));
}
// Edit post
// @see: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
updatePost(id, post) {
const payload = Object.assign({}, post, { id });
const params = Object.assign({}, this.baseParams, { Item: payload });
return this.dynamodb.put(params).promise()
.then(() => ({ post: payload }));
}
// Delete post
// @see: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property
deletePost(id) {
const params = Object.assign({}, this.baseParams,
{ Key: { id } }
);
return this.dynamodb.delete(params).promise();
}
}
module.exports = BlogStorage;
# Insert under handler for the posts function
postsRequest:
handler: handler.request
events:
- http:
path: posts
method: get
cors: true
- http:
path: posts
method: post
cors: true
- http:
path: posts/{id}
method: put
cors: true
- http:
path: posts/{id}
method: delete
cors: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment