dynamodb-service
Managing records saved in Dynamodb
Scenario
I want to save scheduling information
{
recurrence: string,
time: string,
timeZone: string,
mediumType: enum,
meta: json
}
Goal
Create node package that exposes a DynamoDBService
along with CRUD methods.
example usage
const DynamoDBService = require('dynamodb-service');
let dynamoDBService = new DynamoDBService(tableName, primaryKeyName, profile);
dynamoDBService.create(data)
pre-requisite
- Create a credentials file at ~/.aws/credentials on Mac/Linux or C:\Users\USERNAME.aws\credentials on Windows
[default]
aws_access_key_id = your_access_key
aws_secret_access_key = your_secret_key
[not-default]
aws_access_key_id = your_access_key
aws_secret_access_key = your_secret_key
Other ways to provide credentials
aws dynamodb create-table --table-name scheduling-configuration \
--attribute-definitions AttributeName=configurationId,AttributeType=S \
--key-schema AttributeName=configurationId,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 \
--query TableDescription.TableArn --output text \
--region=us-east-1 --profile default
Step by step
The TDD way
mkdir dynamodb-service
- add initial npm packge files
cd dynamodb-service && npm init
// follow the prompt and provide all required info
mkdir test
- Create and add logic to the test file
let DynamoDBService = require('../index.js');
let tableName = 'scheduling-configuration',
primaryKeyName = 'configurationId';
let dynamodbService = new DynamodbService(tableName, primaryKeyName);
let data = {
recurrence: 'string',
time: 'string',
timeZone: 'string',
mediumType: 'SLACK',
meta: { channelId: 'string', slackBotId: 'string', slackBotName: 'string' }
};
dynamoDBService.create(data)
.then(createdRecord => console.log(createdRecord))
.catch(e => console.error(e.message || 'error', e));
node test/create.test.js
- Create and add logic to the
index.js
file
'use strict';
const DynamoDBService = require('./src/services/DynamoDBService');
module.exports = DynamoDBService;
- Create
DynamoDBService
file
...
constructor(tableName, primaryKeyName, profile) {
this.tableName = tableName;
this.primaryKeyName = primaryKeyName;
let credentials = new AWS.SharedIniFileCredentials({profile});
AWS.config.credentials = credentials;
this.DYNAMO_DB = new AWS.DynamoDB.DocumentClient();
}
...
- Add logic for create method
...
let params = {
TableName: this.tableName,
Item: data
};
return this.dynamoDb.put(params).promise()
.then(() => this.read(data[this.keyName]));
...
- Add logic for read method
...
let Key = {};
Key[this.keyName] = id;
let params = {
TableName: this.tableName,
Key
};
return this.dynamoDb.get(params).promise()
.then(function (response) {
return response.Item;
});
...
resource