Skip to content

Instantly share code, notes, and snippets.

@daaru00
Last active February 13, 2021 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daaru00/901b89c64605b04d0dfe7bcf883ccad0 to your computer and use it in GitHub Desktop.
Save daaru00/901b89c64605b04d0dfe7bcf883ccad0 to your computer and use it in GitHub Desktop.
DynamoDB model helper (with promise wrapper)
const DynamoDB = require('aws-sdk/clients/dynamodb')
const documentClient = new DynamoDB.DocumentClient({
apiVersion: '2012-08-10',
// logger: console
})
module.exports = class Model {
/**
* Model constructor
*
* @param {String} tableName
*/
constructor(tableName) {
this.tableName = tableName
}
/**
* DynamoDB query wrapper
*
* @param {*} params
*/
async query(params) {
params.TableName = this.tableName
return documentClient.query(params).promise()
}
/**
* DynamoDB get wrapper
*
* @param {*} keys
*/
async get(keys, params) {
params = params || {}
params.TableName = this.tableName
params.Key = keys
return documentClient.get(params).promise()
}
/**
* DynamoDB scan wrapper
*
* @param {*} keys
*/
async scan(params) {
params = params || {}
params.TableName = this.tableName
return documentClient.scan(params).promise()
}
/**
* DynamoDB put wrapper
*
* @param {*} item
*/
async put(item) {
return documentClient.put({
TableName: this.tableName,
Item: item,
}).promise()
}
/**
* DynamoDB batchWrite wrapper
*
* @param {Array} items
*/
async putBatch(items) {
const requestItems = {}
requestItems[this.tableName] = items.map((item) => ({
PutRequest: {
Item: item
}
}))
return documentClient.batchWrite({
RequestItems: requestItems
}).promise()
}
/**
* DynamoDB batchWrite wrapper
*
* @param {Array} items
*/
async deleteBatch(keys) {
const requestItems = {}
requestItems[this.tableName] = keys.map((key) => ({
DeleteRequest: {
Key: key
}
}))
return documentClient.batchWrite({
RequestItems: requestItems
}).promise()
}
/**
* DynamoDB update wrapper
*
* @param {*} params
*/
async update(params) {
params.TableName = this.tableName
return documentClient.update(params).promise()
}
}
const AbstractModel = require('./abstract')
class Model extends AbstractModel {
/**
* Custom method
*/
async isDone(id) {
const doc = await this.get({id})
return doc.done === true
}
}
module.exports = new Model(process.env.TABLE_TODO)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment