dynopromise-client
Version:
A client for dynamodb using promises.
62 lines (51 loc) • 1.96 kB
JavaScript
const AWS = require('aws-sdk')
// Methods of the AWS DynamoDB DocumentClient to use in promisified db.
const methodsToOverride = ['batchGet', 'batchWrite', 'createSet', 'delete',
'get', 'put', 'query', 'scan', 'update']
module.exports = options => {
// Give options argument first-priority and fallback to environment variable
// settings. If nothing is present, an empty object will be based to the
// DocumentClient constructor and it will fail to initialise.
const realOptions = options || {}
if (!realOptions.region && process.env.DYNOPROMISE_AWS_REGION) {
realOptions.region = process.env.DYNOPROMISE_AWS_REGION
}
if (!realOptions.endpoint && process.env.DYNOPROMISE_DYNAMODB_ENDPOINT) {
realOptions.endpoint = process.env.DYNOPROMISE_DYNAMODB_ENDPOINT
}
if (!realOptions.accessKeyId && !realOptions.secretAccessKey &&
process.env.DYNOPROMISE_AWS_ACCESS_KEY_ID &&
process.env.DYNOPROMISE_AWS_SECRET_ACCESS_KEY) {
realOptions.accessKeyId = process.env.DYNOPROMISE_AWS_ACCESS_KEY_ID
realOptions.secretAccessKey =
process.env.DYNOPROMISE_AWS_SECRET_ACCESS_KEY
}
// Create underlying document client.
const client = new AWS.DynamoDB.DocumentClient(realOptions)
// Interface for the promisified db.
const db = {}
// Function to bind new db methods to AWS document client methods.
const callDb = (method, params) => new Promise((resolve, reject) => {
client[method](params, (err, data) => {
if (err) {
return reject(err)
}
return resolve(data)
})
})
// Promisfy db API methods.
for (let method in client) {
// Only override the methods which are documented.
if (methodsToOverride.indexOf(method) >= 0) {
Object.defineProperty(db, method, {
enumerable: true,
value: params => callDb(method, params)
})
}
}
Object.defineProperty(db, 'getDocumentClient', {
enumerable: true,
value: () => client
})
return db
}