UNPKG

dynafixtures

Version:

Fixtures for DynamoDB

137 lines (121 loc) 3.26 kB
'use strict'; /* jshint -W079 */ // "Redefinition of event" var _port = 4567, _delay = 300; // Delay for the dynamodb table creation state var async = require('async'), aws = require('aws-sdk'), fs = require('fs'), _db; var addTables = function(tables, callback) { async.eachLimit( tables, 1, function(params, done) { _db.createTable(params, done); }, function(err) { if (err) { callback(err); return; } setTimeout(callback, _delay); } ); }; // Set up a Dynalite server var initialize = function(tables, port, callback) { // Load tables if not object and then add them if (typeof tables === 'string') { fs.readFile(tables, function(err, file){ if (err) { callback(err); return; } addTables(JSON.parse(file.toString()), callback); }); } else if (typeof tables === 'object') { addTables(tables, callback); } }; // Remove all tables var teardown = function(callback) { _db.listTables(function(err, data){ async.each( data.TableNames, function(table, done){ _db.deleteTable({ TableName: table }, done); }, callback ); }); }; // Create records var fixture = function(params, callback) { if (typeof params === 'string') { fs.readFile(params, function(err, file){ if (err) { callback(err); return; } _db.batchWriteItem(JSON.parse(file.toString()), callback); }); } else if (typeof params === 'object') { _db.batchWriteItem(params, callback); } }; // Create fixtures for multiple tables var fixtures = function(fixtures, callback) { async.each( fixtures, function(file, done){ if (typeof file === 'string') { fs.readFile(file, function(err, file){ if (err) { done(err); return; } var params = JSON.parse(file.toString()); fixture(params, done); }); } else if (typeof file === 'object') { fixture(file, done); } }, callback ); }; // Set up tables and fixtured in one function. // This is just a shorthand for initialize and fixtures. var setup = function(tables, fixtureArray, port, callback) { if (typeof port === 'number') { _port = port; } // Create a dynamodb instance to add tables _db = new aws.DynamoDB({ 'accessKeyId': 'a', 'secretAccessKey':'b', 'endpoint':'http://localhost:'+_port, 'region': 'eu-west-1' }); teardown(function(){ initialize(tables, port, function(err){ if (err) { callback(err); return; } fixtures(fixtureArray, callback); }); }); }; exports.initialize = initialize; exports.teardown = teardown; exports.fixture = fixture; exports.fixtures = fixtures; exports.setup = setup;