Skip to content

Instantly share code, notes, and snippets.

@yohanesws
Created March 19, 2019 12:36
Show Gist options
  • Select an option

  • Save yohanesws/6a3e6edf384b3f14d7eb2cfc8e6e988d to your computer and use it in GitHub Desktop.

Select an option

Save yohanesws/6a3e6edf384b3f14d7eb2cfc8e6e988d to your computer and use it in GitHub Desktop.
s3 to dynamodb
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
const parseS3Event = require('./parse-s3-event');
const TABLE_NAME = process.env.TABLE_NAME;
exports.handler = (event) => {
let S3Objects = parseS3Event(event);
return Promise.all(S3Objects.map(saveToDynamoDB));
};
saveToDynamoDB = (data) => {
if (!data) {
return Promise.resolve();
}
let params = {
TableName: TABLE_NAME,
Item: {
'title' : data.key,
'author' : 'upload',
'genre' : 'ebook',
'price' : 'free'
}
}
return docClient.put(params)
.promise()
.then(response => response)
.catch(err => {
console.log(err);
return err;
});
};
module.exports = (event) => {
if (!event || !event.Records || !Array.isArray(event.Records)) {
return [];
}
let extractMessage = record => record.s3 && record.s3.object;
return event.Records.map(extractMessage).filter(object => object);
};
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: An AWS Serverless Specification template describing your function.
Resources:
uploadEbook:
Type: 'AWS::Serverless::Function'
Properties:
Handler: index.handler
Runtime: nodejs8.10
CodeUri: .
Description: ''
MemorySize: 128
Timeout: 3
Role: 'arn:aws:iam::294235872584:role/service-role/DynamoDBCrudPolicy'
Events:
BucketEvent1:
Type: S3
Properties:
Bucket:
Ref: Bucket1
Events:
- 's3:ObjectCreated:*'
Environment:
Variables:
TABLE_NAME: book_table
Bucket1:
Type: 'AWS::S3::Bucket'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment