UNPKG

@incdevco/framework

Version:
468 lines (254 loc) 7.97 kB
var crypto = require('crypto'); var AWS = require('aws-sdk'); var moment = require('moment'); var Promise = require('bluebird'); var uuid = require('uuid/v4'); module.exports.copy = function (original) { 'use strict'; var copy; if (original && typeof original === 'object') { copy = JSON.parse(JSON.stringify(original)); } else { copy = original; } return copy; }; module.exports.createAwsApiGatewayStageEndpoint = function (restApiId, stage, region) { 'use strict'; var endpoint = 'https://'; if (!restApiId || restApiId === '') { throw new Error('The rest api id must be submitted'); } if (!restApiId || restApiId === '') { throw new Error('The stage must be submitted'); } region = region || AWS.config.region; if (!region || region === '') { throw new Error('The aws region must be set or submitted'); } endpoint += restApiId; endpoint += '.execute-api.'; endpoint += region; endpoint += '.amazonaws.com/' + stage; return endpoint; }; module.exports.createId = function (length) { 'use strict'; return crypto.randomBytes(length).toString('hex').substr(0, length); }; module.exports.ddbBatchWriteUntilComplete = function (ddb, requestItems) { 'use strict'; function doBatchWriteItem(requestItems) { return ddb.batchWriteItem({ RequestItems: requestItems }).promise() .then(function (result) { if (Object.keys(result.UnprocessedItems).length) { return doBatchWriteItem(result.UnprocessedItems); } else { return true; } }); } return doBatchWriteItem(requestItems); }; module.exports.ddbEmptyStringsToNull = function (input) { var self = this; if (typeof input === 'object' && input !== null && input !== undefined) { if (Array.isArray(input)) { input.forEach(function (element) { if (typeof element === 'object') { self.ddbEmptyStringsToNull(element); } else if (element === '') { element = null; } }); } else { Object.keys(input).forEach(function(key) { if (typeof input[key] === 'object') { self.ddbEmptyStringsToNull(input[key]); } else if (input[key] === '') { input[key] = null; } }); } } }; module.exports.ddbIsConditionalException = function (exception) { if (exception.code === 'ConditionalCheckFailedException') { return true; } else { return false; } }; module.exports.ddbQueryUntilComplete = function (ddb, params) { 'use strict'; var items = []; function doQuery(params, lastEvaluatedKey) { if (lastEvaluatedKey) { params.ExclusiveStartKey = lastEvaluatedKey; } return ddb.query(params).promise() .then(function (result) { result.Items.forEach(function (item) { items.push(item); }); if (result.LastEvaluatedKey) { return doQuery(params, result.LastEvaluatedKey); } else { return true; } }); } return doQuery(params) .then(function () { return items; }); }; module.exports.ddbScanUntilComplete = function (ddb, params) { 'use strict'; var items = []; function doScan(params, lastEvaluatedKey) { if (lastEvaluatedKey) { params.ExclusiveStartKey = lastEvaluatedKey; } return ddb.scan(params).promise() .then(function (result) { result.Items.forEach(function (item) { items.push(item); }); if (result.LastEvaluatedKey) { return doScan(params, result.LastEvaluatedKey); } else { return true; } }); } return doScan(params) .then(function () { return items; }); }; module.exports.getCurrentEpoch = function () { 'use strict'; return Math.floor((new Date().valueOf()) / 1000); }; module.exports.getCurrentTimestamp = function () { 'use strict'; return new Date().valueOf(); }; module.exports.getMoment = function () { 'use strict' return moment(); }; module.exports.isDDBConditionalException = function (exception) { 'use strict'; return this.ddbIsConditionalException(exception); }; module.exports.merge = function () { 'use strict'; var args, merged = {}; args = Array.from(arguments); args.forEach(function (arg) { if (arg) { Object.keys(arg).forEach(function(key) { merged[key] = arg[key]; }); } }); return merged; }; module.exports.millisecondsInADay = 86400000; module.exports.millisecondsInAHour = 3600000; module.exports.millisecondsInAWeek = 604800000; module.exports.randNumber = function (length) { var min = '1'; var max = '9'; for (var i = 1; i < length; i++) { min += '0'; max += '9'; } min = parseInt(min); max = parseInt(max); return this.randomNumberInclusive(min, max); }; module.exports.randomNumberInclusive = function (minimum, maximum) { 'use strict'; return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; }; module.exports.secondsInADay = 86400; module.exports.secondsInAHour = 3600; module.exports.secondsInAWeek = 604800; module.exports.setLastUpdatedFromRequest = function (request, model, options) { options = options || { last_updated_key: 'last_updated', last_updated_user_values: [ 'id', 'name', 'role' ] }; model[options.last_updated_key] = { epoch: this.getCurrentEpoch(), user: null }; if (request.user) { model[options.last_updated_key].user = {}; options.last_updated_user_values.forEach(function (key) { model[options.last_updated_key].user[key] = request.user[key]; }); } }; module.exports.sqsSendMessageBatch = function (sqs, queueUrl, messages) { 'use strict'; var batch = [], batches = [], promise = Promise.resolve(true), results = []; messages.forEach(function (message, index) { if (batch.length >= 10) { batches.push(batch); batch = []; } message.Id = message.Id || index; batch.push(message); }); batches.forEach(function (batch) { promise = promise.then(function () { return sqs.sendMessageBatch({ Entries: batch, QueueUrl: queueUrl }).promise() .then(function (result) { if (result.Failed && result.Failed.length) { throw result; } results = results.concat(result.Successful); return result; }); }); }); return promise .then(function () { return results; }); }; module.exports.ucfirst = function (string) { 'use strict'; return string.charAt(0).toUpperCase() + string.slice(1); }; module.exports.unique = function (input) { var output; if (!Array.isArray(input)) { throw new Error('input must be in array: ' + typeof input); } output = input.concat(); for (var i = 0; i < output.length; i++) { for (var j = i+1; j < output.length; j++) { if (output[i] === output[j]) { output.splice(j--, 1); } } } return output; }; module.exports.uuid = uuid;