From 77fbdad09a1147ed2a37175280bf4a39ef42eeb0 Mon Sep 17 00:00:00 2001 From: Charlie Fish Date: Sun, 17 Feb 2019 15:22:42 -0700 Subject: [PATCH] style(lint): fixing future lint warnings --- lib/Attribute.js | 373 +++--- lib/Listener.js | 4 +- lib/Model.js | 508 +++++---- lib/Plugin.js | 12 +- lib/Query.js | 221 ++-- lib/Scan.js | 325 +++--- lib/Schema.js | 94 +- lib/Table.js | 302 +++-- lib/VirtualType.js | 6 +- lib/errors.js | 24 +- lib/index.js | 76 +- lib/reserved-keywords.js | 4 +- release.config.js | 2 +- test/General.js | 6 +- test/LocalDB.js | 20 +- test/Model.js | 2309 ++++++++++++++++++-------------------- test/Plugin.js | 494 ++++---- test/Query.js | 528 ++++----- test/Scan.js | 552 ++++----- test/Schema.js | 1126 ++++++++++--------- test/Table.js | 270 +++-- test/fixtures/Cats.js | 488 ++++---- 22 files changed, 3810 insertions(+), 3934 deletions(-) diff --git a/lib/Attribute.js b/lib/Attribute.js index 6e2e40bd6..254743525 100644 --- a/lib/Attribute.js +++ b/lib/Attribute.js @@ -2,11 +2,11 @@ const debug = require('debug')('dynamoose:attribute'); const errors = require('./errors'); -function Attribute(schema, name, value) { +function Attribute (schema, name, value) { this.options = {}; debug('Creating attribute %s %o', name, value); - if (value.type){ + if (value.type) { this.options = value; } @@ -19,8 +19,8 @@ function Attribute(schema, name, value) { this.setType(value); } - if(!schema.useDocumentTypes) { - if(this.type.name === 'map') { + if (!schema.useDocumentTypes) { + if (this.type.name === 'map') { debug('Overwriting attribute %s type to object', name); this.type = this.types.object; } else if (this.type.name === 'list') { @@ -30,7 +30,7 @@ function Attribute(schema, name, value) { } if (schema.useNativeBooleans) { - if(this.type.name === 'boolean') { + if (this.type.name === 'boolean') { debug('Overwriting attribute %s type to be a native boolean', name); this.type = this.types.nativeBoolean; } @@ -38,27 +38,26 @@ function Attribute(schema, name, value) { this.attributes = {}; - if (this.type.name === 'map'){ + if (this.type.name === 'map') { - if(value.type) { + if (value.type) { if (!value.map) { throw new errors.SchemaError(`No map schema given for attribute: ${this.name}`); } value = value.map; } - for (const subattrName in value){ - if(this.attributes[subattrName]) { + for (const subattrName in value) { + if (this.attributes[subattrName]) { throw new errors.SchemaError(`Duplicate attribute: ${subattrName} in ${this.name}`); } this.attributes[subattrName] = module.exports.create(schema, subattrName, value[subattrName]); } - } - else if (this.type.name === 'list'){ + } else if (this.type.name === 'list') { - if(value.type) { - if (!value.list || !value.list[0]){ + if (value.type) { + if (!value.list || !value.list[0]) { throw new errors.SchemaError(`No list schema given for attribute: ${this.name}`); } value = value.list; @@ -76,60 +75,52 @@ function Attribute(schema, name, value) { } - if (this.options){ + if (this.options) { this.applyDefault(this.options.default); this.required = this.options.required; if (this.options.set) { if (typeof this.options.set === 'function') { this.set = this.options.set; + } else if (this.options.set.isAsync) { + this.set = function (val) { + return new Promise((resolve) => this.options.set.set(val, (result) => resolve(result))); + }; } else { - if (this.options.set.isAsync) { - this.set = function (val) { - return new Promise(resolve => this.options.set.set(val, result => resolve(result))); - }; - } else { - this.set = this.options.set.set; - } + this.set = this.options.set.set; } } if (this.options.fromDynamo) { if (typeof this.options.fromDynamo === 'function') { this.parseDynamoCustom = this.options.fromDynamo; + } else if (this.options.fromDynamo.isAsync) { + this.parseDynamoCustom = function (val) { + return new Promise((resolve) => this.options.fromDynamo.fromDynamo(val, (result) => resolve(result))); + }; } else { - if (this.options.fromDynamo.isAsync) { - this.parseDynamoCustom = function (val) { - return new Promise(resolve => this.options.fromDynamo.fromDynamo(val, result => resolve(result))); - }; - } else { - this.parseDynamoCustom = this.options.fromDynamo.fromDynamo; - } + this.parseDynamoCustom = this.options.fromDynamo.fromDynamo; } } if (this.options.toDynamo) { if (typeof this.options.toDynamo === 'function') { this.toDynamoCustom = this.options.toDynamo; + } else if (this.options.toDynamo.isAsync) { + this.toDynamoCustom = function (val) { + return new Promise((resolve) => this.options.toDynamo.toDynamo(val, (result) => resolve(result))); + }; } else { - if (this.options.toDynamo.isAsync) { - this.toDynamoCustom = function (val) { - return new Promise(resolve => this.options.toDynamo.toDynamo(val, result => resolve(result))); - }; - } else { - this.toDynamoCustom = this.options.toDynamo.toDynamo; - } + this.toDynamoCustom = this.options.toDynamo.toDynamo; } } if (this.options.get) { if (typeof this.options.get === 'function') { this.get = this.options.get; + } else if (this.options.get.isAsync) { + this.get = function (val) { + return new Promise((resolve) => this.options.get.get(val, (result) => resolve(result))); + }; } else { - if (this.options.get.isAsync) { - this.get = function (val) { - return new Promise(resolve => this.options.get.get(val, result => resolve(result))); - }; - } else { - this.get = this.options.get.get; - } + this.get = this.options.get.get; } } @@ -140,87 +131,87 @@ function Attribute(schema, name, value) { } -function datify(v) { - if(!v.getTime) { +function datify (v) { + if (!v.getTime) { v = new Date(v); } return JSON.stringify(v.getTime()); } Attribute.prototype.types = { - string: { - name: 'string', - dynamo: 'S' + 'string': { + 'name': 'string', + 'dynamo': 'S' }, - number: { - name: 'number', - dynamo: 'N' + 'number': { + 'name': 'number', + 'dynamo': 'N' }, - boolean: { - name: 'boolean', - dynamo: 'S', - dynamofy: JSON.stringify + 'boolean': { + 'name': 'boolean', + 'dynamo': 'S', + 'dynamofy': JSON.stringify }, - nativeBoolean: { - name: 'boolean', - dynamo: 'BOOL' + 'nativeBoolean': { + 'name': 'boolean', + 'dynamo': 'BOOL' }, - date: { - name: 'date', - dynamo: 'N', - dynamofy: datify + 'date': { + 'name': 'date', + 'dynamo': 'N', + 'dynamofy': datify }, - object: { - name: 'object', - dynamo: 'S', - dynamofy: JSON.stringify + 'object': { + 'name': 'object', + 'dynamo': 'S', + 'dynamofy': JSON.stringify }, - array: { - name: 'array', - dynamo: 'S', - dynamofy: JSON.stringify + 'array': { + 'name': 'array', + 'dynamo': 'S', + 'dynamofy': JSON.stringify }, - map: { - name: 'map', - dynamo: 'M', - dynamofy: JSON.stringify + 'map': { + 'name': 'map', + 'dynamo': 'M', + 'dynamofy': JSON.stringify }, - list: { - name: 'list', - dynamo: 'L', - dynamofy: JSON.stringify + 'list': { + 'name': 'list', + 'dynamo': 'L', + 'dynamofy': JSON.stringify }, - buffer: { - name: 'buffer', - dynamo: 'B' + 'buffer': { + 'name': 'buffer', + 'dynamo': 'B' } }; -Attribute.prototype.setTypeFromRawValue = function(value) { - //no type defined - assume this is not a type definition and we must grab type directly from value +Attribute.prototype.setTypeFromRawValue = function (value) { + // no type defined - assume this is not a type definition and we must grab type directly from value let type; let typeVal = value; - if (value.type){ + if (value.type) { typeVal = value.type; } - if (Array.isArray(typeVal) || typeVal === 'list'){ + if (Array.isArray(typeVal) || typeVal === 'list') { type = 'List'; - } else if ( (Array.isArray(typeVal) && typeVal.length === 1) || typeof typeVal === 'function') { + } else if (Array.isArray(typeVal) && typeVal.length === 1 || typeof typeVal === 'function') { this.isSet = Array.isArray(typeVal); - let regexFuncName = /^Function ([^(]+)\(/i; - let found = typeVal.toString().match(regexFuncName); + const regexFuncName = /^Function ([^(]+)\(/i; + const found = typeVal.toString().match(regexFuncName); type = found[1]; if (type === 'Object') { type = 'Map'; } - } else if (typeof typeVal === 'object' || typeVal === 'map'){ + } else if (typeof typeVal === 'object' || typeVal === 'map') { type = 'Map'; } else { type = typeof typeVal; } - if(!type) { + if (!type) { throw new errors.SchemaError(`Invalid attribute type: ${type}`); } @@ -228,37 +219,37 @@ Attribute.prototype.setTypeFromRawValue = function(value) { this.type = this.types[type]; - if(!this.type) { + if (!this.type) { throw new errors.SchemaError(`Invalid attribute type: ${type}`); } }; -Attribute.prototype.setType = function(value) { - if(!value) { +Attribute.prototype.setType = function (value) { + if (!value) { throw new errors.SchemaError(`Invalid attribute value: ${value}`); } let type; let typeVal = value; - if (value.type){ + if (value.type) { typeVal = value.type; } - if (Array.isArray(typeVal) && typeVal.length === 1 && typeof typeVal[0] === 'object'){ + if (Array.isArray(typeVal) && typeVal.length === 1 && typeof typeVal[0] === 'object') { type = 'List'; - } else if ( (Array.isArray(typeVal) && typeVal.length === 1) || typeof typeVal === 'function') { + } else if (Array.isArray(typeVal) && typeVal.length === 1 || typeof typeVal === 'function') { this.isSet = Array.isArray(typeVal); - let regexFuncName = /^Function ([^(]+)\(/i; - let found = typeVal.toString().match(regexFuncName); + const regexFuncName = /^Function ([^(]+)\(/i; + const found = typeVal.toString().match(regexFuncName); type = found[1]; - } else if (typeof typeVal === 'object'){ + } else if (typeof typeVal === 'object') { type = 'Map'; } else if (typeof typeVal === 'string') { type = typeVal; } - if(!type) { + if (!type) { throw new errors.SchemaError(`Invalid attribute type: ${type}`); } @@ -266,34 +257,34 @@ Attribute.prototype.setType = function(value) { this.type = this.types[type]; - if(!this.type) { + if (!this.type) { throw new errors.SchemaError(`Invalid attribute type: ${type}`); } }; -Attribute.prototype.applyDefault = function(dflt) { - if(dflt === null || dflt === undefined){ +Attribute.prototype.applyDefault = function (dflt) { + if (dflt === null || dflt === undefined) { delete this.default; - } else if(typeof dflt === 'function') { + } else if (typeof dflt === 'function') { this.default = dflt; } else { - this.default = function() { + this.default = function () { return dflt; }; } }; -Attribute.prototype.applyValidation = function(validator) { - if(validator === null || validator === undefined) { +Attribute.prototype.applyValidation = function (validator) { + if (validator === null || validator === undefined) { delete this.validator; - } else if(typeof validator === 'function') { + } else if (typeof validator === 'function') { this.validator = validator; - } else if(validator.constructor.name === 'RegExp') { + } else if (validator.constructor.name === 'RegExp') { this.validator = function (val) { return validator.test(val); }; } else if (typeof validator === 'object') { - let method = validator.validator || validator.validate; + const method = validator.validator || validator.validate; if (validator.isAsync) { this.validator = function (val, model) { return new Promise((resolve) => { @@ -316,92 +307,92 @@ Attribute.prototype.applyValidation = function(validator) { } }; -Attribute.prototype.applyIndexes = function(indexes) { - if(indexes === null || indexes === undefined) { +Attribute.prototype.applyIndexes = function (indexes) { + if (indexes === null || indexes === undefined) { delete this.indexes; return; } - let attr = this; + const attr = this; attr.indexes = {}; - function applyIndex(i) { - if(typeof i !== 'object') { + function applyIndex (i) { + if (typeof i !== 'object') { i = {}; } - let index = {}; + const index = {}; - if(i.global) { + if (i.global) { index.global = true; - if(i.rangeKey) { + if (i.rangeKey) { index.rangeKey = i.rangeKey; } - if(i.throughput) { + if (i.throughput) { let throughput = i.throughput; - if(typeof throughput === 'number') { - throughput = {read: throughput, write: throughput}; + if (typeof throughput === 'number') { + throughput = {'read': throughput, 'write': throughput}; } index.throughput = throughput; - if((!index.throughput.read || !index.throughput.write) && index.throughput.read >= 1 && index.throughput.write >= 1) { - throw new errors.SchemaError('Invalid Index throughput: '+ index.throughput); + if ((!index.throughput.read || !index.throughput.write) && index.throughput.read >= 1 && index.throughput.write >= 1) { + throw new errors.SchemaError(`Invalid Index throughput: ${index.throughput}`); } } else { index.throughput = attr.schema.throughput; } } - if(i.name) { + if (i.name) { index.name = i.name; } else { index.name = attr.name + (i.global ? 'GlobalIndex' : 'LocalIndex'); } - if(i.project !== null && i.project !== undefined) { + if (i.project !== null && i.project !== undefined) { index.project = i.project; } else { index.project = true; } - if(attr.indexes[index.name]) { + if (attr.indexes[index.name]) { throw new errors.SchemaError(`Duplicate index names: ${index.name}`); } attr.indexes[index.name] = index; } - if(Array.isArray(indexes)) { + if (Array.isArray(indexes)) { indexes.map(applyIndex); } else { applyIndex(indexes); } }; -Attribute.prototype.setDefault = async function(model) { +Attribute.prototype.setDefault = async function (model) { if (model === undefined || model === null) { return; } - let val = model[this.name]; + const val = model[this.name]; if ((val === null || val === undefined || val === '' || this.options.forceDefault) && this.default) { model[this.name] = await this.default(model); - debug('Defaulted %s to %s', this.name, model[this.name]); + debug('Defaulted %s to %s', this.name, model[this.name]); } }; -Attribute.prototype.toDynamo = async function(val, noSet, model, options) { +Attribute.prototype.toDynamo = async function (val, noSet, model, options) { if (this.toDynamoCustom) { return this.toDynamoCustom(val, noSet, model, options); } - if(val === null || val === undefined || val === '') { - if(this.required) { + if (val === null || val === undefined || val === '') { + if (this.required) { throw new errors.ValidationError(`Required value missing: ${this.name}`); } return null; } - if (!noSet && this.isSet){ + if (!noSet && this.isSet) { if (!Array.isArray(val)) { throw new errors.ValidationError(`Values must be array: ${this.name}`); } @@ -410,7 +401,7 @@ Attribute.prototype.toDynamo = async function(val, noSet, model, options) { } } - if (this.validator && !(await this.validator(val, model))) { + if (this.validator && !await this.validator(val, model)) { throw new errors.ValidationError(`Validation failed: ${this.name}`); } @@ -424,7 +415,7 @@ Attribute.prototype.toDynamo = async function(val, noSet, model, options) { isTimestamp = true; } - if (model && model.$__ && model.$__.schema && model.$__.schema.expires && (model.$__.schema.expires.attribute === this.name)) { + if (model && model.$__ && model.$__.schema && model.$__.schema.expires && model.$__.schema.expires.attribute === this.name) { isExpires = true; } @@ -442,13 +433,13 @@ Attribute.prototype.toDynamo = async function(val, noSet, model, options) { } - let type = this.type; + const type = this.type; const isSet = this.isSet && !noSet; - let dynamoObj = {}; + const dynamoObj = {}; - if(isSet) { - dynamoObj[`${type.dynamo}S`] = val.map(function(v) { + if (isSet) { + dynamoObj[`${type.dynamo}S`] = val.map((v) => { if (type.dynamofy) { return type.dynamofy(v); } @@ -466,10 +457,10 @@ Attribute.prototype.toDynamo = async function(val, noSet, model, options) { } return v; - }.bind(this)); + }); } else if (type.name === 'map') { - let dynamoMapObj = {}; - for(const [name, value] of Object.entries(val)) { + const dynamoMapObj = {}; + for (const [name, value] of Object.entries(val)) { let subAttr = this.attributes[name]; // if saveUnknown is activated the input has an unknown attribute, let's create one on the fly. if (!subAttr && (this.schema.options.saveUnknown || Array.isArray(this.options.saveUnknown) && this.options.saveUnknown.indexOf(name) >= 0)) { @@ -490,14 +481,14 @@ Attribute.prototype.toDynamo = async function(val, noSet, model, options) { throw new errors.ValidationError(`Values must be array in a 'list': ${this.name}`); } - let dynamoList = []; + const dynamoList = []; for (let i = 0; i < val.length; i += 1) { const item = val[i]; // TODO currently only supports one attribute type const objAttr = this.attributes[0]; - if (objAttr){ + if (objAttr) { await objAttr.setDefault(model); dynamoList.push(await objAttr.toDynamo(item, undefined, model)); } @@ -539,12 +530,12 @@ Attribute.prototype.toDynamo = async function(val, noSet, model, options) { }; -Attribute.prototype.parseDynamo = async function(json) { +Attribute.prototype.parseDynamo = async function (json) { if (this.parseDynamoCustom) { return this.parseDynamoCustom(json); } - async function dedynamofy(type, isSet, json, transform, attr) { + async function dedynamofy (type, isSet, json, transform, attr) { const errorHandlingTransform = transform && async function (v) { try { return await transform(v, attr); @@ -554,32 +545,32 @@ Attribute.prototype.parseDynamo = async function(json) { } }; - if(!json){ + if (!json) { return; } - if(isSet) { + if (isSet) { const set = json[`${type}S`]; - return (await Promise.all(set.map(async function (v) { - if(errorHandlingTransform) { + return await Promise.all(set.map(async (v) => { + if (errorHandlingTransform) { return await errorHandlingTransform(v); } return v; - }))); + })); } const val = json[type]; - if(errorHandlingTransform) { - return (await errorHandlingTransform((val !== undefined) ? val : json)); + if (errorHandlingTransform) { + return await errorHandlingTransform(val !== undefined ? val : json); } return val; } - async function mapify(v, attr){ - if(!v){ return; } - let val = {}; + async function mapify (v, attr) { + if (!v) { return; } + const val = {}; - const { attributes, schema } = attr; + const {attributes, schema} = attr; // loop over all the properties of the input - for(const [name, value] of Object.entries(v)) { + for (const [name, value] of Object.entries(v)) { let subAttr = attributes[name]; // if saveUnknown is activated the input has an unknown attribute, let's create one on the fly. if (!subAttr && schema.options.errorUnknown) { @@ -591,7 +582,7 @@ Attribute.prototype.parseDynamo = async function(json) { } if (subAttr) { const attrVal = await subAttr.parseDynamo(value); - if(attrVal !== undefined && attrVal !== null){ + if (attrVal !== undefined && attrVal !== null) { val[name] = attrVal; } } @@ -599,18 +590,18 @@ Attribute.prototype.parseDynamo = async function(json) { return val; } - async function listify(v, attr){ - if(!v){ return; } - let val = []; + async function listify (v, attr) { + if (!v) { return; } + const val = []; debug('parsing list'); - if (Array.isArray(v)){ + if (Array.isArray(v)) { - for (let i = 0; i < v.length ; i += 1){ + for (let i = 0; i < v.length; i += 1) { // TODO assume only one attribute type allowed for a list const attrType = attr.attributes[0]; const attrVal = await attrType.parseDynamo(v[i]); - if(attrVal !== undefined && attrVal !== null){ + if (attrVal !== undefined && attrVal !== null) { val.push(attrVal); } } @@ -618,15 +609,15 @@ Attribute.prototype.parseDynamo = async function(json) { return val; } - function datify(v) { + function datify (v) { debug('parsing date from %s', v); return new Date(parseInt(v, 10)); } - function bufferify(v) { + function bufferify (v) { return Buffer.from(v); } - function stringify(v){ - if (typeof v !== 'string'){ + function stringify (v) { + if (typeof v !== 'string') { debug('******', v); return JSON.stringify(v); } @@ -636,7 +627,7 @@ Attribute.prototype.parseDynamo = async function(json) { let val; - switch(this.type.name) { + switch (this.type.name) { case 'string': val = await dedynamofy('S', this.isSet, json, stringify, this); break; @@ -670,7 +661,7 @@ Attribute.prototype.parseDynamo = async function(json) { } - if(this.get) { + if (this.get) { val = await this.get(val); } @@ -701,10 +692,10 @@ Attribute.prototype.parseDynamo = async function(json) { * }, * } */ -function createAttrDefFromDynamo(dynamoAttribute) { +function createAttrDefFromDynamo (dynamoAttribute) { let dynamoType; - let attrDef = { - type: module.exports.lookupType(dynamoAttribute), + const attrDef = { + 'type': module.exports.lookupType(dynamoAttribute) }; if (attrDef.type === Object) { attrDef.type = 'map'; @@ -724,7 +715,7 @@ function createAttrDefFromDynamo(dynamoAttribute) { } -const createUnknownAttributeFromDynamo = module.exports.createUnknownAttributeFromDynamo = function(schema, name, dynamoAttribute) { +const createUnknownAttributeFromDynamo = module.exports.createUnknownAttributeFromDynamo = function (schema, name, dynamoAttribute) { debug('createUnknownAttributeFromDynamo: %j : "%s" : %j', schema, name, dynamoAttribute); const attrDef = createAttrDefFromDynamo(dynamoAttribute); @@ -733,38 +724,38 @@ const createUnknownAttributeFromDynamo = module.exports.createUnknownAttributeFr }; -module.exports.create = function(schema, name, obj) { +module.exports.create = function (schema, name, obj) { debug('create: %j : "%s" : %j', schema, name, obj); const value = obj; let options = {}; - if(typeof obj === 'object' && obj.type) { + if (typeof obj === 'object' && obj.type) { options = obj; } const attr = new Attribute(schema, name, value); - if(options.hashKey && options.rangeKey) { + if (options.hashKey && options.rangeKey) { throw new errors.SchemaError(`Cannot be both hashKey and rangeKey: ${name}`); } - if(options.hashKey || (!schema.hashKey && !options.rangeKey)) { + if (options.hashKey || !schema.hashKey && !options.rangeKey) { schema.hashKey = attr; } - if(options.rangeKey) { + if (options.rangeKey) { schema.rangeKey = attr; } // check for global attributes in the tree.. - if(attr.indexes) { - for(const indexName in attr.indexes) { + if (attr.indexes) { + for (const indexName in attr.indexes) { const index = attr.indexes[indexName]; - if(schema.indexes.global[indexName] || schema.indexes.local[indexName]) { + if (schema.indexes.global[indexName] || schema.indexes.local[indexName]) { throw new errors.SchemaError(`Duplicate index name: ${indexName}`); } - if(index.global) { + if (index.global) { schema.indexes.global[indexName] = attr; } else { schema.indexes.local[indexName] = attr; @@ -777,7 +768,7 @@ module.exports.create = function(schema, name, obj) { module.exports.lookupType = function (dynamoObj) { - if(dynamoObj.S !== null && dynamoObj.S !== undefined) { + if (dynamoObj.S !== null && dynamoObj.S !== undefined) { // try { // JSON.parse(dynamoObj.S); // return Object; @@ -785,22 +776,22 @@ module.exports.lookupType = function (dynamoObj) { return String; // } } - if(dynamoObj.L !== null && dynamoObj.L !== undefined) { + if (dynamoObj.L !== null && dynamoObj.L !== undefined) { return Array; } - if(dynamoObj.M !== null && dynamoObj.M !== undefined) { + if (dynamoObj.M !== null && dynamoObj.M !== undefined) { return Object; } - if(dynamoObj.N !== null && dynamoObj.N !== undefined) { + if (dynamoObj.N !== null && dynamoObj.N !== undefined) { return Number; } - if(dynamoObj.BOOL !== null && dynamoObj.BOOL !== undefined) { + if (dynamoObj.BOOL !== null && dynamoObj.BOOL !== undefined) { return Boolean; } - if(dynamoObj.B !== null && dynamoObj.B !== undefined) { + if (dynamoObj.B !== null && dynamoObj.B !== undefined) { return Buffer; } - if(dynamoObj.NS !== null && dynamoObj.NS !== undefined) { + if (dynamoObj.NS !== null && dynamoObj.NS !== undefined) { return [Number]; } }; diff --git a/lib/Listener.js b/lib/Listener.js index cb06945d9..9ad1fb3d3 100644 --- a/lib/Listener.js +++ b/lib/Listener.js @@ -1,4 +1,4 @@ -function Listener(type, stage, func, plugin) { +function Listener (type, stage, func, plugin) { this.type = type; this.stage = stage; this.func = func; @@ -21,7 +21,7 @@ Listener.prototype.emit = async function (type, stage, obj) { return result; } catch (e) { this._debug(`Error running emit on plugin ${obj.plugin.name}`); - return; + } }; diff --git a/lib/Model.js b/lib/Model.js index fc272b582..695b16232 100644 --- a/lib/Model.js +++ b/lib/Model.js @@ -12,33 +12,33 @@ const errors = require('./errors'); const reservedKeywords = require('./reserved-keywords'); const objectPath = require('object-path'); -//const MAX_BATCH_READ_SIZE = 100; -const MAX_BATCH_WRITE_SIZE = 25; +// const MAX_BATCH_READ_SIZE = 100; +const MAX_BATCH_WRITE_SIZE = 25; const debug = require('debug')('dynamoose:model'); -function Model(obj) { +function Model (obj) { this.$__.isNew = true; - for(const key in obj) { + for (const key in obj) { this[key] = obj[key]; } } -async function processCondition(req, options, schema) { +async function processCondition (req, options, schema) { if (options.condition) { - if(req.ConditionExpression) { + if (req.ConditionExpression) { req.ConditionExpression = `(${req.ConditionExpression}) and (${options.condition})`; } else { req.ConditionExpression = options.condition; } - if(options.conditionNames) { + if (options.conditionNames) { req.ExpressionAttributeNames = {}; - for(const name in options.conditionNames) { + for (const name in options.conditionNames) { req.ExpressionAttributeNames[`#${name}`] = options.conditionNames[name]; } } - if(options.conditionValues) { + if (options.conditionValues) { req.ExpressionAttributeValues = {}; const keys = Object.keys(options.conditionValues); for (let i = 0; i < keys.length; i += 1) { @@ -46,7 +46,7 @@ async function processCondition(req, options, schema) { const val = options.conditionValues[k]; const attr = schema.attributes[k]; - if(attr) { + if (attr) { req.ExpressionAttributeValues[`:${k}`] = await attr.toDynamo(val); } else { throw new errors.ModelError(`Invalid condition value: ${k}. The name must either be in the schema or a full DynamoDB object must be specified.`); @@ -59,7 +59,7 @@ async function processCondition(req, options, schema) { Model.compile = function compile (name, schema, options, base) { debug('compiling NewModel %s', name); - let table = new Table(name, schema, options, base); + const table = new Table(name, schema, options, base); function NewModel (obj) { Model.call(this, obj); @@ -69,7 +69,7 @@ Model.compile = function compile (name, schema, options, base) { // Set NewModel.name to match name of table. Original property descriptor // values are reused. - let nameDescriptor = Object.getOwnPropertyDescriptor(NewModel, 'name'); + const nameDescriptor = Object.getOwnPropertyDescriptor(NewModel, 'name'); // Skip if 'name' property can not be redefined. This probably means // code is running in a "non-standard, pre-ES2015 implementations", // like node 0.12. @@ -82,22 +82,22 @@ Model.compile = function compile (name, schema, options, base) { // minimize what is restricted NewModel.prototype.$__ = { - table: table, - base: base, - name: name, - schema: schema, - options: options, - NewModel: NewModel, - plugins: [] + table, + base, + name, + schema, + options, + NewModel, + 'plugins': [] }; NewModel.$__ = NewModel.prototype.$__; - NewModel.plugin = function(pluginPackage, options) { - var obj = { - event: { - plugin: pluginPackage, - pluginOptions: options + NewModel.plugin = function (pluginPackage, options) { + const obj = { + 'event': { + 'plugin': pluginPackage, + 'pluginOptions': options } }; // Emit plugin type `plugin:register` with stage `pre` @@ -110,13 +110,13 @@ Model.compile = function compile (name, schema, options, base) { this._emit('plugin:register', 'post', obj); }; - NewModel.clearAllPlugins = function() { + NewModel.clearAllPlugins = function () { debug('Clearing all plugins'); this.$__.plugins = []; }; // This is a private function that is only used to emit signals to plugins within the Dynamoose plugin, this function should not be documentated or used outside of Dynamoose. - NewModel._emit = async function(type, stage, obj, deferred) { + NewModel._emit = async function (type, stage, obj, deferred) { if (!obj) { obj = {}; @@ -145,7 +145,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.prototype.originalItem = function () { return this.$__.originalItem; }; - NewModel.prototype.model = function(modelName) { + NewModel.prototype.model = function (modelName) { const models = this.$__.base.models; if (!models.hasOwnProperty(modelName)) { const errorMsg = `Schema hasn't been registered for model "${modelName}".\nUse dynamoose.model(name, schema)`; @@ -158,7 +158,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.get = function (key, options, next) { try { return Model.get(NewModel, key, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -167,7 +167,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.populate = function (options, resultObj, fillPath) { try { return Model.populate(options, resultObj, fillPath); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options); return Q.reject(err); } @@ -176,7 +176,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.update = function (key, update, options, next) { try { return Model.update(NewModel, key, update, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -185,7 +185,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.delete = function (key, options, next) { try { return Model.delete(NewModel, key, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -194,7 +194,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.query = function (query, options, next) { try { return Model.query(NewModel, query, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -203,7 +203,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.queryOne = function (query, options, next) { try { return Model.queryOne(NewModel, query, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -212,7 +212,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.scan = function (filter, options, next) { try { return Model.scan(NewModel, filter, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -221,7 +221,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.create = function (obj, options, next) { try { return Model.create(NewModel, obj, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -230,7 +230,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.batchGet = function (keys, options, next) { try { return Model.batchGet(NewModel, keys, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -239,7 +239,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.batchPut = function (keys, options, next) { try { return Model.batchPut(NewModel, keys, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -248,7 +248,7 @@ Model.compile = function compile (name, schema, options, base) { NewModel.batchDelete = function (keys, options, next) { try { return Model.batchDelete(NewModel, keys, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } @@ -258,20 +258,20 @@ Model.compile = function compile (name, schema, options, base) { return table.waitForActive(timeout, next); }; - NewModel.getTableReq = function() { + NewModel.getTableReq = function () { return table.buildTableReq(table.name, table.schema); }; NewModel.conditionCheck = function (key, options, next) { try { return Model.conditionCheck(NewModel, key, options, next); - } catch(err) { + } catch (err) { sendErrorToCallback(err, options, next); return Q.reject(err); } }; - function createTransactionFunction(func, val, optionsIndex) { + function createTransactionFunction (func, val, optionsIndex) { return async function (...args) { if (typeof args[args.length - 1] === 'function') { console.warning('Dynamoose Warning: Passing callback function into transaction method not allowed. Removing callback function from list of arguments.'); @@ -280,12 +280,12 @@ Model.compile = function compile (name, schema, options, base) { } // Adding returnRequest to options - if (args.length >= (optionsIndex + 1)) { - args[optionsIndex] = {...args[optionsIndex], returnRequest: true}; + if (args.length >= optionsIndex + 1) { + args[optionsIndex] = {...args[optionsIndex], 'returnRequest': true}; } else if (args.length < optionsIndex) { - args[optionsIndex] = {returnRequest: true}; + args[optionsIndex] = {'returnRequest': true}; } else { - args.push({returnRequest: true}); + args.push({'returnRequest': true}); } const requestObj = await func(...args); @@ -302,11 +302,11 @@ Model.compile = function compile (name, schema, options, base) { // key - the key to be attached to the returned request object to pass into the DynamoDB transaciton request // name - the name to attach to the resulting object for NewModel.transaction // optionsIndex - the zero-based index for where the options parameter should be in the method arguments list - {method: NewModel.get, key: 'Get', name: 'get', optionsIndex: 1}, - {method: NewModel.delete, key: 'Delete', name: 'delete', optionsIndex: 1}, - {method: NewModel.create, key: 'Put', name: 'create', optionsIndex: 1}, - {method: NewModel.update, key: 'Update', name: 'update', optionsIndex: 2}, - {method: NewModel.conditionCheck, key: 'ConditionCheck', name: 'conditionCheck', optionsIndex: 1} + {'method': NewModel.get, 'key': 'Get', 'name': 'get', 'optionsIndex': 1}, + {'method': NewModel.delete, 'key': 'Delete', 'name': 'delete', 'optionsIndex': 1}, + {'method': NewModel.create, 'key': 'Put', 'name': 'create', 'optionsIndex': 1}, + {'method': NewModel.update, 'key': 'Update', 'name': 'update', 'optionsIndex': 2}, + {'method': NewModel.conditionCheck, 'key': 'ConditionCheck', 'name': 'conditionCheck', 'optionsIndex': 1} ].reduce((original, newItem) => { original[newItem.name] = createTransactionFunction(newItem.method, newItem.key, newItem.optionsIndex); return original; @@ -321,8 +321,8 @@ Model.compile = function compile (name, schema, options, base) { NewModel[k] = hooks[k]; } - table.init(function (err) { - if(err) { + table.init((err) => { + if (err) { throw err; } }); @@ -330,11 +330,11 @@ Model.compile = function compile (name, schema, options, base) { return NewModel; }; -function sendErrorToCallback(error, options, next) { - if(typeof options === 'function') { +function sendErrorToCallback (error, options, next) { + if (typeof options === 'function') { next = options; } - if(typeof next === 'function') { + if (typeof next === 'function') { next(error); } } @@ -346,7 +346,7 @@ function sendErrorToCallback(error, options, next) { * @param {Model} model * @param {Schema} schema */ -const applyMethods = function(model, schema) { +const applyMethods = function (model, schema) { debug('applying methods'); for (const i in schema.methods) { model.prototype[i] = schema.methods[i]; @@ -358,7 +358,7 @@ const applyMethods = function(model, schema) { * @param {Model} model * @param {Schema} schema */ -const applyStatics = function(model, schema) { +const applyStatics = function (model, schema) { debug('applying statics'); for (const i in schema.statics) { model[i] = schema.statics[i].bind(model); @@ -370,45 +370,45 @@ const applyStatics = function(model, schema) { * @param {Model} model * @param {Schema} schema */ -const applyVirtuals = function(model, schema){ +const applyVirtuals = function (model, schema) { debug('applying virtuals'); - for (const i in schema.virtuals){ + for (const i in schema.virtuals) { schema.virtuals[i].applyVirtuals(model); } }; -function validKeyValue(value) { +function validKeyValue (value) { return value !== undefined && value !== null && value !== ''; } -Model.conditionCheck = async function(NewModel, key, options, next) { +Model.conditionCheck = async function (NewModel, key, options, next) { debug('Condition Check', this); const deferred = Q.defer(); try { options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } - let schema = NewModel.$__.schema; - let hashKeyName = schema.hashKey.name; + const schema = NewModel.$__.schema; + const hashKeyName = schema.hashKey.name; - if(!validKeyValue(key[hashKeyName])) { - let keyVal = key; + if (!validKeyValue(key[hashKeyName])) { + const keyVal = key; key = {}; key[hashKeyName] = keyVal; } - if(schema.rangeKey && !validKeyValue(key[schema.rangeKey.name])) { + if (schema.rangeKey && !validKeyValue(key[schema.rangeKey.name])) { deferred.reject(new errors.ModelError(`Range key required: ${schema.rangeKey.name}`)); return deferred.promise.nodeify(next); } - let conditionReq = { - TableName: NewModel.$__.name, - Key: {} + const conditionReq = { + 'TableName': NewModel.$__.name, + 'Key': {} }; try { conditionReq.Key[hashKeyName] = schema.hashKey.toDynamo(key[hashKeyName], undefined, key); @@ -416,35 +416,35 @@ Model.conditionCheck = async function(NewModel, key, options, next) { deferred.reject(e); } - if(schema.rangeKey) { - let rangeKeyName = schema.rangeKey.name; + if (schema.rangeKey) { + const rangeKeyName = schema.rangeKey.name; conditionReq.Key[rangeKeyName] = schema.rangeKey.toDynamo(key[rangeKeyName], undefined, key); } processCondition(conditionReq, options, schema); debug('Condition Check', conditionReq); deferred.resolve(conditionReq); - } catch(err) { + } catch (err) { deferred.reject(err); } return deferred.promise.nodeify(next); }; -Model.prototype.put = async function(options, next) { - var self = this; +Model.prototype.put = async function (options, next) { + const self = this; debug('put', this); const deferred = Q.defer(); - let shouldContinue = await this.$__.NewModel._emit('model:put', 'put:called', {event: {callback: next, options: options}, actions: {updateCallback: function(cb) {next = cb;}, updateOptions: function(newOptions) {options = newOptions;}}}, deferred); + const shouldContinue = await this.$__.NewModel._emit('model:put', 'put:called', {'event': {'callback': next, options}, 'actions': {'updateCallback' (cb) { next = cb; }, 'updateOptions' (newOptions) { options = newOptions; }}}, deferred); if (shouldContinue === false) { return; } let model, model$, item; - async function putItem() { - let shouldContinue = await self.$__.NewModel._emit('model:put', 'request:pre', {event: {options: options, item: item}, actions: {updateItem: function(newItem) {item = newItem;}}}, deferred); + async function putItem () { + const shouldContinue = await self.$__.NewModel._emit('model:put', 'request:pre', {'event': {options, item}, 'actions': {'updateItem' (newItem) { item = newItem; }}}, deferred); if (shouldContinue === false) { return; } - model$.base.ddb().putItem(item, async function(err) { - let shouldContinue = await self.$__.NewModel._emit('model:put', 'request:post', {event: {options: options, item: item, error: err}, actions: {updateError: function(newErr) {err = newErr;}}}, deferred); + model$.base.ddb().putItem(item, async (err) => { + const shouldContinue = await self.$__.NewModel._emit('model:put', 'request:post', {'event': {options, item, 'error': err}, 'actions': {'updateError' (newErr) { err = newErr; }}}, deferred); if (shouldContinue === false) { return; } - if(err) { + if (err) { deferred.reject(err); } deferred.resolve(model); @@ -453,16 +453,16 @@ Model.prototype.put = async function(options, next) { try { options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } - if(options.overwrite === null || options.overwrite === undefined) { + if (options.overwrite === null || options.overwrite === undefined) { options.overwrite = true; } - let toDynamoOptions = { - updateTimestamps: true + const toDynamoOptions = { + 'updateTimestamps': true }; if (options.updateTimestamps === false) { @@ -473,15 +473,15 @@ Model.prototype.put = async function(options, next) { toDynamoOptions.updateExpires = true; } - let schema = this.$__.schema; + const schema = this.$__.schema; item = { - TableName: this.$__.name, - Item: await schema.toDynamo(this, toDynamoOptions) + 'TableName': this.$__.name, + 'Item': await schema.toDynamo(this, toDynamoOptions) }; await schema.parseDynamo(this, item.Item); - if(!options.overwrite) { + if (!options.overwrite) { if (!reservedKeywords.isReservedKeyword(schema.hashKey.name) && !schema.hashKey.name.startsWith('_')) { item.ConditionExpression = `attribute_not_exists(${schema.hashKey.name})`; } else { @@ -504,7 +504,7 @@ Model.prototype.put = async function(options, next) { } else { putItem(); } - } catch(err) { + } catch (err) { deferred.reject(err); } return deferred.promise.nodeify(next); @@ -512,15 +512,15 @@ Model.prototype.put = async function(options, next) { Model.prototype.save = Model.prototype.put; -Model.create = function(NewModel, obj, options, next) { +Model.create = function (NewModel, obj, options, next) { options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } - if(options.overwrite === null || options.overwrite === undefined) { + if (options.overwrite === null || options.overwrite === undefined) { options.overwrite = false; } @@ -528,19 +528,19 @@ Model.create = function(NewModel, obj, options, next) { return model.save(options, next); }; -Model.get = async function(NewModel, key, options, next) { +Model.get = async function (NewModel, key, options, next) { debug('Get %j', key); const deferred = Q.defer(); - let shouldContinue = await NewModel._emit('model:get', 'get:called', {event: {callback: next, key: key, options: options}, actions: {updateCallback: function(cb) {next = cb;}, updateKey: function(newKey) {key = newKey;}, updateOptions: function(newOptions) {options = newOptions;} }}, deferred); + const shouldContinue = await NewModel._emit('model:get', 'get:called', {'event': {'callback': next, key, options}, 'actions': {'updateCallback' (cb) { next = cb; }, 'updateKey' (newKey) { key = newKey; }, 'updateOptions' (newOptions) { options = newOptions; }}}, deferred); if (shouldContinue === false) { return; } options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } - if(key === null || key === undefined) { + if (key === null || key === undefined) { deferred.reject(new errors.ModelError('Key required to get item')); return deferred.promise.nodeify(next); } @@ -553,21 +553,21 @@ Model.get = async function(NewModel, key, options, next) { return deferred.promise.nodeify(next); } - if(!validKeyValue(key[hashKeyName])) { - let keyVal = key; + if (!validKeyValue(key[hashKeyName])) { + const keyVal = key; key = {}; key[hashKeyName] = keyVal; } - if(schema.rangeKey && !validKeyValue(key[schema.rangeKey.name])) { + if (schema.rangeKey && !validKeyValue(key[schema.rangeKey.name])) { deferred.reject(new errors.ModelError(`Range key required: ${schema.rangeKey.name}`)); return deferred.promise.nodeify(next); } let getReq = { - TableName: NewModel.$__.name, - Key: {} + 'TableName': NewModel.$__.name, + 'Key': {} }; try { @@ -576,45 +576,45 @@ Model.get = async function(NewModel, key, options, next) { deferred.reject(e); } - if(schema.rangeKey) { - let rangeKeyName = schema.rangeKey.name; + if (schema.rangeKey) { + const rangeKeyName = schema.rangeKey.name; getReq.Key[rangeKeyName] = await schema.rangeKey.toDynamo(key[rangeKeyName], undefined, key); } - if(options.attributes) { + if (options.attributes) { getReq.AttributesToGet = options.attributes; } - if(options.consistent) { + if (options.consistent) { getReq.ConsistentRead = true; } - let newModel$ = NewModel.$__; + const newModel$ = NewModel.$__; async function get () { debug('getItem', getReq); - let shouldContinue = await NewModel._emit('model:get', 'request:pre', {event: {callback: next, key: key, options: options, getRequest: getReq}, actions: {updateCallback: function(cb) {next = cb;}, updateKey: function(newKey) {key = newKey;}, updateOptions: function(newOptions) {options = newOptions;}, updateGetRequest: function(newReq) {getReq = newReq;} }}, deferred); + const shouldContinue = await NewModel._emit('model:get', 'request:pre', {'event': {'callback': next, key, options, 'getRequest': getReq}, 'actions': {'updateCallback' (cb) { next = cb; }, 'updateKey' (newKey) { key = newKey; }, 'updateOptions' (newOptions) { options = newOptions; }, 'updateGetRequest' (newReq) { getReq = newReq; }}}, deferred); if (shouldContinue === false) { return; } - newModel$.base.ddb().getItem(getReq, async function(err, data) { - let shouldContinue = await NewModel._emit('model:get', 'request:post', {event: {callback: next, key: key, options: options, error: err, data: data}, actions: {updateCallback: function(cb) {next = cb;}, updateKey: function(newKey) {key = newKey;}, updateOptions: function(newOptions) {options = newOptions;}, updateError: function(newErr) {err = newErr;}, updateData: function(newData) {data = newData;} }}, deferred); + newModel$.base.ddb().getItem(getReq, async (err, data) => { + const shouldContinue = await NewModel._emit('model:get', 'request:post', {'event': {'callback': next, key, options, 'error': err, data}, 'actions': {'updateCallback' (cb) { next = cb; }, 'updateKey' (newKey) { key = newKey; }, 'updateOptions' (newOptions) { options = newOptions; }, 'updateError' (newErr) { err = newErr; }, 'updateData' (newData) { data = newData; }}}, deferred); if (shouldContinue === false) { return; } - if(err) { + if (err) { debug('Error returned by getItem', err); return deferred.reject(err); } debug('getItem response', data); - if(!Object.keys(data).length) { + if (!Object.keys(data).length) { return deferred.resolve(); } - let model = new NewModel(); + const model = new NewModel(); model.$__.isNew = false; try { await schema.parseDynamo(model, data.Item); - } catch(e){ + } catch (e) { debug('cannot parse data', data); return deferred.reject(e); } @@ -677,7 +677,7 @@ Model.prototype.populate = function (options, resultObj, fillPath) { return Model .get(this[options.path || options]) - .then(target => { + .then((target) => { if (!target) { throw new Error('Invalid reference'); } @@ -686,9 +686,9 @@ Model.prototype.populate = function (options, resultObj, fillPath) { objectPath.set(resultObj, fillPath, target); if (options.populate) { return this[options.path || options].populate(options.populate, resultObj, fillPath); - } else { - return resultObj; } + return resultObj; + }); }; @@ -700,22 +700,22 @@ Model.prototype.populate = function (options, resultObj, fillPath) { // }); // NewModel.update({id: 123}, { $PUT: {a: 1, b: 2} }); // NewModel.update({id: 123}, {a: 1, b: 2} ); // Defaults to put (same as above)*/ -Model.update = async function(NewModel, key, update, options, next) { +Model.update = async function (NewModel, key, update, options, next) { debug('Update %j', key); const deferred = Q.defer(); const schema = NewModel.$__.schema; - if(typeof update === 'function') { + if (typeof update === 'function') { next = update; update = null; } - if(update === undefined || update === null) { + if (update === undefined || update === null) { update = key; } options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } @@ -740,7 +740,7 @@ Model.update = async function(NewModel, key, update, options, next) { key = {}; // first figure out the primary/hash key - let hashKeyDefault = schema.attributes[schema.hashKey.name].options.default; + const hashKeyDefault = schema.attributes[schema.hashKey.name].options.default; if (typeof hashKeyDefault === 'undefined') { deferred.reject(new errors.ModelError('Key required to get item')); @@ -751,7 +751,7 @@ Model.update = async function(NewModel, key, update, options, next) { // now see if you have to figure out a range key if (schema.rangeKey) { - let rangeKeyDefault = schema.attributes[schema.rangeKey.name].options.default; + const rangeKeyDefault = schema.attributes[schema.rangeKey.name].options.default; if (typeof rangeKeyDefault === 'undefined') { deferred.reject(new errors.ModelError(`Range key required: ${schema.rangeKey.name}`)); @@ -762,66 +762,66 @@ Model.update = async function(NewModel, key, update, options, next) { } } - let hashKeyName = schema.hashKey.name; - if(!key[hashKeyName]) { - let keyVal = key; + const hashKeyName = schema.hashKey.name; + if (!key[hashKeyName]) { + const keyVal = key; key = {}; key[hashKeyName] = keyVal; } - let updateReq = { - TableName: NewModel.$__.name, - Key: {}, - ExpressionAttributeNames: {}, - ExpressionAttributeValues: {}, - ReturnValues: options.returnValues + const updateReq = { + 'TableName': NewModel.$__.name, + 'Key': {}, + 'ExpressionAttributeNames': {}, + 'ExpressionAttributeValues': {}, + 'ReturnValues': options.returnValues }; await processCondition(updateReq, options, NewModel.$__.schema); updateReq.Key[hashKeyName] = await schema.hashKey.toDynamo(key[hashKeyName], undefined, key); - if(schema.rangeKey) { - let rangeKeyName = schema.rangeKey.name; + if (schema.rangeKey) { + const rangeKeyName = schema.rangeKey.name; updateReq.Key[rangeKeyName] = await schema.rangeKey.toDynamo(key[rangeKeyName]), undefined, key; } // determine the set of operations to be executed - function Operations() { + function Operations () { this.ifNotExistsSet = {}; this.SET = {}; this.ADD = {}; this.REMOVE = {}; this.LISTAPPEND = {}; - this.addIfNotExistsSet = function(name, item) { + this.addIfNotExistsSet = function (name, item) { this.ifNotExistsSet[name] = item; }; - this.addSet = function(name, item) { - if(schema.hashKey.name !== name && (schema.rangeKey || {}).name !== name) { + this.addSet = function (name, item) { + if (schema.hashKey.name !== name && (schema.rangeKey || {}).name !== name) { this.SET[name] = item; } }; - this.addListAppend = function(name, item) { - if(schema.hashKey.name !== name && (schema.rangeKey || {}).name !== name) { + this.addListAppend = function (name, item) { + if (schema.hashKey.name !== name && (schema.rangeKey || {}).name !== name) { this.LISTAPPEND[name] = item; } }; - this.addAdd = function(name, item) { - if(schema.hashKey.name !== name && (schema.rangeKey || {}).name !== name) { + this.addAdd = function (name, item) { + if (schema.hashKey.name !== name && (schema.rangeKey || {}).name !== name) { this.ADD[name] = item; } }; - this.addRemove = function(name, item) { - if(schema.hashKey.name !== name && (schema.rangeKey || {}).name !== name) { + this.addRemove = function (name, item) { + if (schema.hashKey.name !== name && (schema.rangeKey || {}).name !== name) { this.REMOVE[name] = item; } }; - this.getUpdateExpression = function(updateReq) { + this.getUpdateExpression = function (updateReq) { let attrCount = 0; let updateExpression = ''; @@ -830,7 +830,7 @@ Model.update = async function(NewModel, key, update, options, next) { let name; let item; - let setExpressions = []; + const setExpressions = []; for (name in this.ifNotExistsSet) { item = this.ifNotExistsSet[name]; @@ -875,7 +875,7 @@ Model.update = async function(NewModel, key, update, options, next) { updateExpression += `SET ${setExpressions.join(',')} `; } - let addExpressions = []; + const addExpressions = []; for (name in this.ADD) { item = this.ADD[name]; @@ -893,7 +893,7 @@ Model.update = async function(NewModel, key, update, options, next) { updateExpression += `ADD ${addExpressions.join(',')} `; } - let removeExpressions = []; + const removeExpressions = []; for (name in this.REMOVE) { item = this.REMOVE[name]; @@ -913,20 +913,20 @@ Model.update = async function(NewModel, key, update, options, next) { }; } - let operations = new Operations(); + const operations = new Operations(); - if (update.$PUT || (!update.$PUT && !update.$DELETE && !update.$ADD)) { - let updatePUT = update.$PUT || update; + if (update.$PUT || !update.$PUT && !update.$DELETE && !update.$ADD) { + const updatePUT = update.$PUT || update; for (const putItem in updatePUT) { - let putAttr = schema.attributes[putItem]; + const putAttr = schema.attributes[putItem]; if (putAttr || schema.options.saveUnknown) { - let val = updatePUT[putItem]; + const val = updatePUT[putItem]; let removeParams = val === null || val === undefined || val === ''; if (!options.allowEmptyArray) { - removeParams = removeParams || (Array.isArray(val) && val.length === 0); + removeParams = removeParams || Array.isArray(val) && val.length === 0; } if (removeParams) { @@ -947,12 +947,12 @@ Model.update = async function(NewModel, key, update, options, next) { } } - if(update.$DELETE) { - for(const deleteItem in update.$DELETE) { - let deleteAttr = schema.attributes[deleteItem]; - if(deleteAttr || schema.options.saveUnknown) { - let delVal = update.$DELETE[deleteItem]; - if(delVal !== null && delVal !== undefined) { + if (update.$DELETE) { + for (const deleteItem in update.$DELETE) { + const deleteAttr = schema.attributes[deleteItem]; + if (deleteAttr || schema.options.saveUnknown) { + const delVal = update.$DELETE[deleteItem]; + if (delVal !== null && delVal !== undefined) { try { if (deleteAttr) { operations.addRemove(deleteItem, await deleteAttr.toDynamo(delVal)); @@ -970,10 +970,10 @@ Model.update = async function(NewModel, key, update, options, next) { } } - if(update.$ADD) { - for(const addItem in update.$ADD) { - let addAttr = schema.attributes[addItem]; - let addVal = update.$ADD[addItem]; + if (update.$ADD) { + for (const addItem in update.$ADD) { + const addAttr = schema.attributes[addItem]; + const addVal = update.$ADD[addItem]; try { if (addAttr) { if (addAttr.type.name === 'list') { @@ -1019,7 +1019,7 @@ Model.update = async function(NewModel, key, update, options, next) { // doesn't have a default. if (options.createRequired) { for (const attributeName in schema.attributes) { - let attribute = schema.attributes[attributeName]; + const attribute = schema.attributes[attributeName]; if (attribute.required && // if the attribute is required... attributeName !== schema.hashKey.name && // ...and it isn't the hash key... (!schema.rangeKey || attributeName !== schema.rangeKey.name) && // ...and it isn't the range key... @@ -1029,18 +1029,18 @@ Model.update = async function(NewModel, key, update, options, next) { !operations.ADD[attributeName] && !operations.REMOVE[attributeName]) { - let defaultValueOrFunction = attribute.options.default; + const defaultValueOrFunction = attribute.options.default; // throw an error if you have required attribute without a default (and you didn't supply // anything to update with) if (typeof defaultValueOrFunction === 'undefined') { - let err = `Required attribute "${attributeName}" does not have a default.`; + const err = `Required attribute "${attributeName}" does not have a default.`; debug('Error returned by updateItem', err); deferred.reject(err); return deferred.promise.nodeify(next); } - let defaultValue = typeof defaultValueOrFunction === 'function' ? defaultValueOrFunction() : defaultValueOrFunction; + const defaultValue = typeof defaultValueOrFunction === 'function' ? defaultValueOrFunction() : defaultValueOrFunction; operations.addIfNotExistsSet(attributeName, await attribute.toDynamo(defaultValue)); } @@ -1050,13 +1050,13 @@ Model.update = async function(NewModel, key, update, options, next) { operations.getUpdateExpression(updateReq); // AWS doesn't allow empty expressions or attribute collections - if(!updateReq.UpdateExpression) { + if (!updateReq.UpdateExpression) { delete updateReq.UpdateExpression; } - if(!Object.keys(updateReq.ExpressionAttributeNames).length) { + if (!Object.keys(updateReq.ExpressionAttributeNames).length) { delete updateReq.ExpressionAttributeNames; } - if(!Object.keys(updateReq.ExpressionAttributeValues).length) { + if (!Object.keys(updateReq.ExpressionAttributeValues).length) { delete updateReq.ExpressionAttributeValues; } @@ -1064,14 +1064,14 @@ Model.update = async function(NewModel, key, update, options, next) { function updateItem () { debug('updateItem', updateReq); - newModel$.base.ddb().updateItem(updateReq, async function(err, data) { - if(err) { + newModel$.base.ddb().updateItem(updateReq, async (err, data) => { + if (err) { debug('Error returned by updateItem', err); return deferred.reject(err); } debug('updateItem response', data); - if(!Object.keys(data).length) { + if (!Object.keys(data).length) { return deferred.resolve(); } @@ -1079,7 +1079,7 @@ Model.update = async function(NewModel, key, update, options, next) { model.$__.isNew = false; try { await schema.parseDynamo(model, data.Attributes); - } catch(e){ + } catch (e) { debug('cannot parse data', data); return deferred.reject(e); } @@ -1101,18 +1101,18 @@ Model.update = async function(NewModel, key, update, options, next) { return deferred.promise.nodeify(next); }; -Model.delete = function(NewModel, key, options, next) { +Model.delete = function (NewModel, key, options, next) { const schema = NewModel.$__.schema; const hashKeyName = schema.hashKey.name; - if(!key[hashKeyName]) { + if (!key[hashKeyName]) { const keyVal = key; key = {}; key[hashKeyName] = keyVal; } - if(schema.rangeKey && !key[schema.rangeKey.name]) { + if (schema.rangeKey && !key[schema.rangeKey.name]) { const deferred = Q.defer(); deferred.reject(new errors.ModelError('Range key required: %s', schema.hashKey.name)); return deferred.promise.nodeify(next); @@ -1122,9 +1122,9 @@ Model.delete = function(NewModel, key, options, next) { return model.delete(options, next); }; -Model.prototype.delete = async function(options, next) { +Model.prototype.delete = async function (options, next) { options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } @@ -1135,26 +1135,26 @@ Model.prototype.delete = async function(options, next) { const deferred = Q.defer(); - if(this[hashKeyName] === null || this[hashKeyName] === undefined) { + if (this[hashKeyName] === null || this[hashKeyName] === undefined) { deferred.reject(new errors.ModelError('Hash key required: %s', hashKeyName)); return deferred.promise.nodeify(next); } - if(schema.rangeKey && (this[schema.rangeKey.name] === null || this[schema.rangeKey.name] === undefined)) { + if (schema.rangeKey && (this[schema.rangeKey.name] === null || this[schema.rangeKey.name] === undefined)) { deferred.reject(new errors.ModelError('Range key required: %s', schema.hashKey.name)); return deferred.promise.nodeify(next); } const getDelete = { - TableName: this.$__.name, - Key: {} + 'TableName': this.$__.name, + 'Key': {} }; try { getDelete.Key[hashKeyName] = await schema.hashKey.toDynamo(this[hashKeyName], undefined, this); - if(schema.rangeKey) { + if (schema.rangeKey) { const rangeKeyName = schema.rangeKey.name; getDelete.Key[rangeKeyName] = await schema.rangeKey.toDynamo(this[rangeKeyName], undefined, this); } @@ -1163,7 +1163,7 @@ Model.prototype.delete = async function(options, next) { return deferred.promise.nodeify(next); } - if(options.update) { + if (options.update) { getDelete.ReturnValues = 'ALL_OLD'; getDelete.ConditionExpression = `attribute_exists(${schema.hashKey.name})`; } @@ -1171,17 +1171,17 @@ Model.prototype.delete = async function(options, next) { const model = this; const model$ = this.$__; - function deleteItem() { + function deleteItem () { debug('deleteItem', getDelete); - model$.base.ddb().deleteItem(getDelete, async function(err, data) { - if(err) { + model$.base.ddb().deleteItem(getDelete, async (err, data) => { + if (err) { debug('Error returned by deleteItem', err); return deferred.reject(err); } debug('deleteItem response', data); - if(options.update && data.Attributes) { + if (options.update && data.Attributes) { try { await schema.parseDynamo(model, data.Attributes); debug('deleteItem parsed model', model); @@ -1217,23 +1217,23 @@ query({hash: {id: {eq : 1}}, range: {name: {beginwith: 'foxy'}}}) query({id: 1}) query('id').eq(1).where('name').begienwith('foxy') */ -Model.query = function(NewModel, query, options, next) { - if(typeof options === 'function') { +Model.query = function (NewModel, query, options, next) { + if (typeof options === 'function') { next = options; options = null; } query = new Query(NewModel, query, options); - if(next) { + if (next) { query.exec(next); } return query; }; -Model.queryOne = function(NewModel, query, options, next) { - if(typeof options === 'function') { +Model.queryOne = function (NewModel, query, options, next) { + if (typeof options === 'function') { next = options; options = null; } @@ -1241,7 +1241,7 @@ Model.queryOne = function(NewModel, query, options, next) { query = new Query(NewModel, query, options); query.one(); - if(next) { + if (next) { query.exec(next); } @@ -1261,30 +1261,30 @@ scan('id').between(a, b).and().where('name').begienwith('foxy').exec(); scan().exec(); // All records */ -Model.scan = function(NewModel, filter, options, next) { - if(typeof options === 'function') { +Model.scan = function (NewModel, filter, options, next) { + if (typeof options === 'function') { next = options; options = null; } const scan = new Scan(NewModel, filter, options); - if(next) { + if (next) { scan.exec(next); } return scan; }; -Model.batchGet = async function(NewModel, keys, options, next) { +Model.batchGet = async function (NewModel, keys, options, next) { debug('BatchGet %j', keys); const deferred = Q.defer(); - if(!(Array.isArray(keys))) { + if (!Array.isArray(keys)) { deferred.reject(new errors.ModelError('batchGet requires keys to be an array')); return deferred.promise.nodeify(next); } options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } @@ -1292,8 +1292,8 @@ Model.batchGet = async function(NewModel, keys, options, next) { const schema = NewModel.$__.schema; const hashKeyName = schema.hashKey.name; - keys = keys.map(function (key) { - if(!key[hashKeyName]) { + keys = keys.map((key) => { + if (!key[hashKeyName]) { const ret = {}; ret[hashKeyName] = key; return ret; @@ -1301,34 +1301,34 @@ Model.batchGet = async function(NewModel, keys, options, next) { return key; }); - if(schema.rangeKey && !keys.every(function (key) { return validKeyValue(key[schema.rangeKey.name]); })) { + if (schema.rangeKey && !keys.every((key) => validKeyValue(key[schema.rangeKey.name]))) { deferred.reject(new errors.ModelError(`Range key required: ${schema.rangeKey.name}`)); return deferred.promise.nodeify(next); } const batchReq = { - RequestItems: {} + 'RequestItems': {} }; const getReq = {}; batchReq.RequestItems[NewModel.$__.name] = getReq; - getReq.Keys = await Promise.all(keys.map(async key => { + getReq.Keys = await Promise.all(keys.map(async (key) => { const ret = {}; ret[hashKeyName] = await schema.hashKey.toDynamo(key[hashKeyName], undefined, key); - if(schema.rangeKey) { + if (schema.rangeKey) { const rangeKeyName = schema.rangeKey.name; ret[rangeKeyName] = await schema.rangeKey.toDynamo(key[rangeKeyName], undefined, key); } return ret; })); - if(options.attributes) { + if (options.attributes) { getReq.AttributesToGet = options.attributes; } - if(options.consistent) { + if (options.consistent) { getReq.ConsistentRead = true; } @@ -1336,14 +1336,14 @@ Model.batchGet = async function(NewModel, keys, options, next) { function batchGet () { debug('batchGetItem', batchReq); - newModel$.base.ddb().batchGetItem(batchReq, async function(err, data) { - if(err) { + newModel$.base.ddb().batchGetItem(batchReq, async (err, data) => { + if (err) { debug('Error returned by batchGetItem', err); return deferred.reject(err); } debug('batchGetItem response', data); - if(!Object.keys(data).length) { + if (!Object.keys(data).length) { return deferred.resolve(); } @@ -1357,14 +1357,14 @@ Model.batchGet = async function(NewModel, keys, options, next) { return model; } - const models = data.Responses[newModel$.name] ? (await Promise.all(data.Responses[newModel$.name].map(toModel))).filter(item => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())) : []; + const models = data.Responses[newModel$.name] ? (await Promise.all(data.Responses[newModel$.name].map(toModel))).filter((item) => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())) : []; if (data.UnprocessedKeys[newModel$.name]) { // convert unprocessed keys back to dynamoose format - models.unprocessed = await Promise.all(data.UnprocessedKeys[newModel$.name].Keys.map(async function (key) { + models.unprocessed = await Promise.all(data.UnprocessedKeys[newModel$.name].Keys.map(async (key) => { const ret = {}; ret[hashKeyName] = await schema.hashKey.parseDynamo(key[hashKeyName]); - if(schema.rangeKey) { + if (schema.rangeKey) { const rangeKeyName = schema.rangeKey.name; ret[rangeKeyName] = await schema.rangeKey.parseDynamo(key[rangeKeyName]); } @@ -1376,7 +1376,7 @@ Model.batchGet = async function(NewModel, keys, options, next) { } - if(newModel$.options.waitForActive) { + if (newModel$.options.waitForActive) { newModel$.table.waitForActive().then(batchGet).catch(deferred.reject); } else { batchGet(); @@ -1384,7 +1384,7 @@ Model.batchGet = async function(NewModel, keys, options, next) { return deferred.promise.nodeify(next); }; -async function toBatchChunks(modelName, list, chunkSize, requestMaker) { +async function toBatchChunks (modelName, list, chunkSize, requestMaker) { const listClone = list.slice(0); let chunk = []; const batchChunks = []; @@ -1392,7 +1392,7 @@ async function toBatchChunks(modelName, list, chunkSize, requestMaker) { while ((chunk = listClone.splice(0, chunkSize)).length) { const requests = await Promise.all(chunk.map(requestMaker)); const batchReq = { - RequestItems: {} + 'RequestItems': {} }; batchReq.RequestItems[modelName] = requests; @@ -1402,9 +1402,9 @@ async function toBatchChunks(modelName, list, chunkSize, requestMaker) { return batchChunks; } -function reduceBatchResult(resultList) { +function reduceBatchResult (resultList) { - return resultList.reduce(function(acc, res) { + return resultList.reduce((acc, res) => { const responses = res.Responses ? res.Responses : {}; const unprocessed = res.UnprocessedItems ? res.UnprocessedItems : {}; @@ -1415,7 +1415,7 @@ function reduceBatchResult(resultList) { consumed += responses[tableName].ConsumedCapacityUnits; acc.Responses[tableName] = { - ConsumedCapacityUnits: consumed + 'ConsumedCapacityUnits': consumed }; } } @@ -1430,18 +1430,18 @@ function reduceBatchResult(resultList) { } return acc; - }, {Responses: {}, UnprocessedItems: {}}); + }, {'Responses': {}, 'UnprocessedItems': {}}); } function batchWriteItems (NewModel, batchRequests) { debug('batchWriteItems'); const newModel$ = NewModel.$__; - const batchList = batchRequests.map(function (batchReq) { + const batchList = batchRequests.map((batchReq) => { const deferredBatch = Q.defer(); - newModel$.base.ddb().batchWriteItem(batchReq, function(err, data) { - if(err) { + newModel$.base.ddb().batchWriteItem(batchReq, (err, data) => { + if (err) { debug('Error returned by batchWriteItems', err); return deferredBatch.reject(err); } @@ -1452,21 +1452,19 @@ function batchWriteItems (NewModel, batchRequests) { return deferredBatch.promise; }); - return Q.all(batchList).then(function (resultList) { - return reduceBatchResult(resultList); - }); + return Q.all(batchList).then((resultList) => reduceBatchResult(resultList)); } -Model.batchPut = async function(NewModel, items, options, next) { +Model.batchPut = async function (NewModel, items, options, next) { debug('BatchPut %j', items); const deferred = Q.defer(); - if(!(Array.isArray(items))) { + if (!Array.isArray(items)) { deferred.reject(new errors.ModelError('batchPut requires items to be an array')); return deferred.promise.nodeify(next); } options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } @@ -1475,27 +1473,25 @@ Model.batchPut = async function(NewModel, items, options, next) { const newModel$ = NewModel.$__; const toDynamoOptions = { - updateTimestamps: options.updateTimestamps || false, - updateExpires: options.updateExpires || false + 'updateTimestamps': options.updateTimestamps || false, + 'updateExpires': options.updateExpires || false }; - const batchRequests = await toBatchChunks(newModel$.name, items, MAX_BATCH_WRITE_SIZE, async function(item) { - return { - PutRequest: { - Item: await schema.toDynamo(item, toDynamoOptions) - } - }; - }); + const batchRequests = await toBatchChunks(newModel$.name, items, MAX_BATCH_WRITE_SIZE, async (item) => ({ + 'PutRequest': { + 'Item': await schema.toDynamo(item, toDynamoOptions) + } + })); - const batchPut = function() { - batchWriteItems(NewModel, batchRequests).then(function (result) { + const batchPut = function () { + batchWriteItems(NewModel, batchRequests).then((result) => { deferred.resolve(result); - }).fail(function (err) { + }).fail((err) => { deferred.reject(err); }); }; - if(newModel$.options.waitForActive) { + if (newModel$.options.waitForActive) { newModel$.table.waitForActive().then(batchPut).catch(deferred.reject); } else { batchPut(); @@ -1503,17 +1499,17 @@ Model.batchPut = async function(NewModel, items, options, next) { return deferred.promise.nodeify(next); }; -Model.batchDelete = async function(NewModel, keys, options, next) { +Model.batchDelete = async function (NewModel, keys, options, next) { debug('BatchDel %j', keys); const deferred = Q.defer(); - if(!(Array.isArray(keys))) { + if (!Array.isArray(keys)) { deferred.reject(new errors.ModelError('batchDelete requires keys to be an array')); return deferred.promise.nodeify(next); } options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } @@ -1522,30 +1518,30 @@ Model.batchDelete = async function(NewModel, keys, options, next) { const newModel$ = NewModel.$__; const hashKeyName = schema.hashKey.name; - const batchRequests = await toBatchChunks(newModel$.name, keys, MAX_BATCH_WRITE_SIZE, async function(key) { + const batchRequests = await toBatchChunks(newModel$.name, keys, MAX_BATCH_WRITE_SIZE, async (key) => { const key_element = {}; key_element[hashKeyName] = await schema.hashKey.toDynamo(key[hashKeyName]), undefined, key; - if(schema.rangeKey) { + if (schema.rangeKey) { key_element[schema.rangeKey.name] = await schema.rangeKey.toDynamo(key[schema.rangeKey.name], undefined, key); } return { - DeleteRequest: { - Key: key_element + 'DeleteRequest': { + 'Key': key_element } }; }); - const batchDelete = function() { - batchWriteItems(NewModel, batchRequests).then(function (result) { + const batchDelete = function () { + batchWriteItems(NewModel, batchRequests).then((result) => { deferred.resolve(result); - }).fail(function (err) { + }).fail((err) => { deferred.reject(err); }); }; - if(newModel$.options.waitForActive) { + if (newModel$.options.waitForActive) { newModel$.table.waitForActive().then(batchDelete).catch(deferred.reject); } else { batchDelete(); diff --git a/lib/Plugin.js b/lib/Plugin.js index bb73b148f..ff2b74124 100644 --- a/lib/Plugin.js +++ b/lib/Plugin.js @@ -1,7 +1,7 @@ const debug = require('debug')('dynamoose:plugin'); const Listener = require('./Listener'); -function Plugin(model, func, options, registerPlugin) { +function Plugin (model, func, options, registerPlugin) { this.name = ''; this.description = ''; this.listeners = []; @@ -9,17 +9,17 @@ function Plugin(model, func, options, registerPlugin) { this.registerPlugin = registerPlugin; func({ - setName: (name) => { + 'setName': (name) => { this.name = name; debug(`Set plugin name to ${name}`); }, - setDescription: (description) => { + 'setDescription': (description) => { this.description = description; debug(`Set description to ${description}`); }, // Ability for plugin to add listeners on certain events emmited from Dynamoose - on: (type, stage, func) => { + 'on': (type, stage, func) => { // If type is not passed in then set func to type, and stage to null, and type to null, this will make type an optional catch all parameter if (typeof type === 'function') { func = type; @@ -51,9 +51,7 @@ Plugin.prototype.emit = async function (type, stage, obj) { debug(`Stage: ${stage}`); debug('Filtering listeners that match type and stage'); // filter listeners where type is the same and stage is null or the same - const listenersToRun = this.listeners.filter((listener) => { - return ((!listener.type || listener.type === type) && (!listener.stage || listener.stage === stage)); - }); + const listenersToRun = this.listeners.filter((listener) => (!listener.type || listener.type === type) && (!listener.stage || listener.stage === stage)); // If obj is undefined set to empty object if (!obj) { diff --git a/lib/Query.js b/lib/Query.js index 3060822e2..aa66d0f73 100644 --- a/lib/Query.js +++ b/lib/Query.js @@ -19,54 +19,53 @@ function Query (Model, query, options) { // comparison: 'string' // } // } - this.query = {hashKey: {}}; + this.query = {'hashKey': {}}; this.filters = {}; this.buildState = false; this.validationError = null; let hashKeyName, hashKeyVal; - if(typeof query === 'string') { + if (typeof query === 'string') { this.buildState = 'hashKey'; this.query.hashKey.name = query; } else if (query.hash) { hashKeyName = Object.keys(query.hash)[0]; hashKeyVal = query.hash[hashKeyName]; - if(hashKeyVal.eq !== null && hashKeyVal.eq !== undefined) { + if (hashKeyVal.eq !== null && hashKeyVal.eq !== undefined) { hashKeyVal = hashKeyVal.eq; } this.query.hashKey.name = hashKeyName; this.query.hashKey.value = hashKeyVal; - if(query.range) { + if (query.range) { const rangeKeyName = Object.keys(query.range)[0]; let rangeKeyVal = query.range[rangeKeyName]; const rangeKeyComp = Object.keys(rangeKeyVal)[0]; rangeKeyVal = rangeKeyVal[rangeKeyComp]; this.query.rangeKey = { - name: rangeKeyName, - values: [rangeKeyVal], - comparison: rangeKeyComp + 'name': rangeKeyName, + 'values': [rangeKeyVal], + 'comparison': rangeKeyComp }; } } else { hashKeyName = Object.keys(query)[0]; hashKeyVal = query[hashKeyName]; - if(hashKeyVal.eq !== null && hashKeyVal.eq !== undefined) { + if (hashKeyVal.eq !== null && hashKeyVal.eq !== undefined) { hashKeyVal = hashKeyVal.eq; } this.query.hashKey.name = hashKeyName; this.query.hashKey.value = hashKeyVal; } - Model._emit('model:query', 'query:called', {event: {query: this}}); + Model._emit('model:query', 'query:called', {'event': {'query': this}}); } - Query.prototype.exec = async function (next) { debug('exec query for ', this.query); - var theQuery = this; - this.Model._emit('model:query', 'exec:start', {event: {query: this, callback: next}, actions: {updateCallback: function(fn) {next = fn;}}}); + const theQuery = this; + this.Model._emit('model:query', 'exec:start', {'event': {'query': this, 'callback': next}, 'actions': {'updateCallback' (fn) { next = fn; }}}); if (this.validationError) { if (next) { next(this.validationError); @@ -82,18 +81,18 @@ Query.prototype.exec = async function (next) { debug('Query with schema', schema); let queryReq = { - TableName: Model.$__.name, - KeyConditions: {} + 'TableName': Model.$__.name, + 'KeyConditions': {} }; let indexName, index; // Check both hash key and range key in the query to see if they do not match // the hash and range key on the primary table. If they don't match then we // can look for a secondary index to query. - if(schema.hashKey.name !== this.query.hashKey.name || (this.query.rangeKey && schema.rangeKey && schema.rangeKey.name !== this.query.rangeKey.name)) { - for(indexName in schema.indexes.global) { + if (schema.hashKey.name !== this.query.hashKey.name || this.query.rangeKey && schema.rangeKey && schema.rangeKey.name !== this.query.rangeKey.name) { + for (indexName in schema.indexes.global) { index = schema.indexes.global[indexName]; - if(index.name === this.query.hashKey.name && (!this.query.rangeKey || index.indexes[indexName].rangeKey === this.query.rangeKey.name)) { + if (index.name === this.query.hashKey.name && (!this.query.rangeKey || index.indexes[indexName].rangeKey === this.query.rangeKey.name)) { debug('query is on global secondary index'); debug('using index', indexName); queryReq.IndexName = indexName; @@ -102,24 +101,24 @@ Query.prototype.exec = async function (next) { } } - let hashAttr = schema.attributes[this.query.hashKey.name]; + const hashAttr = schema.attributes[this.query.hashKey.name]; queryReq.KeyConditions[this.query.hashKey.name] = { - AttributeValueList: [await hashAttr.toDynamo(this.query.hashKey.value)], - ComparisonOperator: 'EQ' + 'AttributeValueList': [await hashAttr.toDynamo(this.query.hashKey.value)], + 'ComparisonOperator': 'EQ' }; let i, val; - if(this.query.rangeKey) { - let rangeKey = this.query.rangeKey; - let rangeAttr = schema.attributes[rangeKey.name]; + if (this.query.rangeKey) { + const rangeKey = this.query.rangeKey; + const rangeAttr = schema.attributes[rangeKey.name]; - if(!queryReq.IndexName && schema.rangeKey.name !== rangeKey.name) { + if (!queryReq.IndexName && schema.rangeKey.name !== rangeKey.name) { debug('query is on local secondary index'); - for(indexName in schema.indexes.local) { + for (indexName in schema.indexes.local) { index = schema.indexes.local[indexName]; - if(index.name === rangeKey.name) { + if (index.name === rangeKey.name) { debug('using local index', indexName); queryReq.IndexName = indexName; break; @@ -127,18 +126,18 @@ Query.prototype.exec = async function (next) { } } - if(!rangeKey || rangeKey.values === undefined) { + if (!rangeKey || rangeKey.values === undefined) { debug('No range key value (i.e. get all)'); } else { debug('Range key: %s', rangeKey.name); - let keyConditions = queryReq.KeyConditions[rangeKey.name] = { - AttributeValueList: [], - ComparisonOperator: rangeKey.comparison.toUpperCase() + const keyConditions = queryReq.KeyConditions[rangeKey.name] = { + 'AttributeValueList': [], + 'ComparisonOperator': rangeKey.comparison.toUpperCase() }; for (i = 0; i < rangeKey.values.length; i += 1) { - val = rangeKey.values [i]; + val = rangeKey.values[i]; keyConditions.AttributeValueList.push( - await rangeAttr.toDynamo(val, true, Model, { updateTimestamps: false }) + await rangeAttr.toDynamo(val, true, Model, {'updateTimestamps': false}) ); } } @@ -146,70 +145,70 @@ Query.prototype.exec = async function (next) { // if the index name has been explicitly set via the api then let that override // anything that has been previously derived - if(this.options.indexName){ + if (this.options.indexName) { debug('forcing index: %s', this.options.indexName); queryReq.IndexName = this.options.indexName; } - if(this.filters && Object.keys(this.filters).length > 0) { + if (this.filters && Object.keys(this.filters).length > 0) { queryReq.QueryFilter = {}; - for(const name in this.filters) { + for (const name in this.filters) { debug('Filter on: %s', name); - let filter = this.filters[name]; - let filterAttr = schema.attributes[name]; + const filter = this.filters[name]; + const filterAttr = schema.attributes[name]; queryReq.QueryFilter[name] = { - AttributeValueList: [], - ComparisonOperator: filter.comparison.toUpperCase() + 'AttributeValueList': [], + 'ComparisonOperator': filter.comparison.toUpperCase() }; - let isContains = filter.comparison === 'CONTAINS' || filter.comparison === 'NOT_CONTAINS'; - let isListContains = isContains && filterAttr.type.name === 'list'; + const isContains = filter.comparison === 'CONTAINS' || filter.comparison === 'NOT_CONTAINS'; + const isListContains = isContains && filterAttr.type.name === 'list'; - if(filter.values) { + if (filter.values) { for (i = 0; i < filter.values.length; i += 1) { val = filter.values[i]; queryReq.QueryFilter[name].AttributeValueList.push( - isListContains ? await filterAttr.attributes[0].toDynamo(val, true, Model, {updateTimestamps: false}) : await filterAttr.toDynamo(val, true, Model, {updateTimestamps: false}) + isListContains ? await filterAttr.attributes[0].toDynamo(val, true, Model, {'updateTimestamps': false}) : await filterAttr.toDynamo(val, true, Model, {'updateTimestamps': false}) ); } } } } - if(options.or) { + if (options.or) { queryReq.ConditionalOperator = 'OR'; // defualts to AND } - if(options.attributes) { + if (options.attributes) { queryReq.AttributesToGet = options.attributes; } - if(options.count) { + if (options.count) { queryReq.Select = 'COUNT'; } - if(options.counts) { + if (options.counts) { queryReq.Select = 'COUNT'; } - if(options.consistent) { + if (options.consistent) { queryReq.ConsistentRead = true; } - if(options.limit) { + if (options.limit) { queryReq.Limit = options.limit; } - if(options.one) { + if (options.one) { queryReq.Limit = 1; } - if(options.descending) { + if (options.descending) { queryReq.ScanIndexForward = false; } - if(options.ExclusiveStartKey) { + if (options.ExclusiveStartKey) { queryReq.ExclusiveStartKey = options.ExclusiveStartKey; } @@ -224,25 +223,25 @@ Query.prototype.exec = async function (next) { let models = {}, totalCount = 0, scannedCount = 0, timesQueried = 0, lastKey; queryOne(); - async function queryOne() { + async function queryOne () { debug('DynamoDB Query: %j', queryReq); - let shouldContinue = await theQuery.Model._emit('model:query', 'request:pre', {event: {query: theQuery, callback: next, queryReq: queryReq}, actions: {updateQueryReq: function(req) {queryReq = req;}}}, deferred); + const shouldContinue = await theQuery.Model._emit('model:query', 'request:pre', {'event': {'query': theQuery, 'callback': next, queryReq}, 'actions': {'updateQueryReq' (req) { queryReq = req; }}}, deferred); if (shouldContinue === false) { return; } - Model$.base.ddb().query(queryReq, async function(err, data) { - let shouldContinue = await theQuery.Model._emit('model:query', 'request:post', {event: {query: theQuery, callback: next, data: data, error: err}, actions: {updateError: function(error) {err = error;}, updateData: function(myData) {data = myData;}}}, deferred); + Model$.base.ddb().query(queryReq, async (err, data) => { + const shouldContinue = await theQuery.Model._emit('model:query', 'request:post', {'event': {'query': theQuery, 'callback': next, data, 'error': err}, 'actions': {'updateError' (error) { err = error; }, 'updateData' (myData) { data = myData; }}}, deferred); if (shouldContinue === false) { return; } - if(err) { + if (err) { debug('Error returned by query', err); return deferred.reject(err); } debug('DynamoDB Query Response: %j', data); - if(!Object.keys(data).length) { + if (!Object.keys(data).length) { return deferred.resolve(); } async function toModel (item) { - let model = new Model(); + const model = new Model(); model.$__.isNew = false; await schema.parseDynamo(model, item); @@ -256,7 +255,7 @@ Query.prototype.exec = async function (next) { return deferred.resolve(data.Count); } if (options.counts) { - let counts = { count: data.Count, scannedCount: data.ScannedCount }; + const counts = {'count': data.Count, 'scannedCount': data.ScannedCount}; return deferred.resolve(counts); } if (data.Items !== undefined) { @@ -266,11 +265,11 @@ Query.prototype.exec = async function (next) { models = models.concat(await Promise.all(data.Items.map(toModel))); } - if(options.one) { + if (options.one) { if (!models || models.length === 0) { return deferred.resolve(); } - return deferred.resolve(models.filter(item => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date()))[0]); + return deferred.resolve(models.filter((item) => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date()))[0]); } lastKey = data.LastEvaluatedKey; } @@ -283,7 +282,7 @@ Query.prototype.exec = async function (next) { queryReq.ExclusiveStartKey = lastKey; setTimeout(queryOne, options.all.delay); } else { - models = models.filter(item => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())); + models = models.filter((item) => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())); models.lastKey = lastKey; models.count = totalCount; models.scannedCount = scannedCount; @@ -300,7 +299,7 @@ Query.prototype.exec = async function (next) { } - if(Model$.options.waitForActive) { + if (Model$.options.waitForActive) { return Model$.table.waitForActive().then(query).catch(query); } @@ -312,22 +311,22 @@ Query.prototype.where = function (rangeKey) { if (this.validationError) { return this; } - if(this.buildState) { + if (this.buildState) { this.validationError = new errors.QueryError('Invalid Query state: where() must follow eq()'); return this; } - if(typeof rangeKey === 'string') { + if (typeof rangeKey === 'string') { this.buildState = 'rangeKey'; - this.query.rangeKey = {name: rangeKey}; + this.query.rangeKey = {'name': rangeKey}; } else { const rangeKeyName = Object.keys(rangeKey)[0]; let rangeKeyVal = rangeKey[rangeKeyName]; const rangeKeyComp = Object.keys(rangeKeyVal)[0]; rangeKeyVal = rangeKeyVal[rangeKeyComp]; this.query.rangeKey = { - name: rangeKeyName, - values: [rangeKeyVal], - comparison: rangeKeyComp + 'name': rangeKeyName, + 'values': [rangeKeyVal], + 'comparison': rangeKeyComp }; } @@ -338,18 +337,18 @@ Query.prototype.filter = function (filter) { if (this.validationError) { return this; } - if(this.buildState) { + if (this.buildState) { this.validationError = new errors.QueryError('Invalid Query state: filter() must follow comparison'); return this; } - if(typeof filter === 'string') { + if (typeof filter === 'string') { this.buildState = 'filter'; this.currentFilter = filter; - if(this.filters[filter]) { - this.validationError = new errors.QueryError('Invalid Query state: %s filter can only be used once', filter); + if (this.filters[filter]) { + this.validationError = new errors.QueryError('Invalid Query state: %s filter can only be used once', filter); return this; } - this.filters[filter] = {name: filter}; + this.filters[filter] = {'name': filter}; } return this; @@ -360,15 +359,15 @@ Query.prototype.compVal = function (vals, comp) { if (this.validationError) { return this; } - if(this.buildState === 'hashKey') { - if(comp !== 'EQ') { + if (this.buildState === 'hashKey') { + if (comp !== 'EQ') { this.validationError = new errors.QueryError('Invalid Query state: eq must follow query()'); return this; } this.query.hashKey.value = vals[0]; - } else if (this.buildState === 'rangeKey'){ - if(VALID_RANGE_KEYS.indexOf(comp) < 0) { - this.validationError = new errors.QueryError('Invalid Query state: %s must follow filter()', comp); + } else if (this.buildState === 'rangeKey') { + if (VALID_RANGE_KEYS.indexOf(comp) < 0) { + this.validationError = new errors.QueryError('Invalid Query state: %s must follow filter()', comp); return this; } this.query.rangeKey.values = vals; @@ -377,7 +376,7 @@ Query.prototype.compVal = function (vals, comp) { this.filters[this.currentFilter].values = vals; this.filters[this.currentFilter].comparison = comp; } else { - this.validationError = new errors.QueryError('Invalid Query state: %s must follow query(), where() or filter()', comp); + this.validationError = new errors.QueryError('Invalid Query state: %s must follow query(), where() or filter()', comp); return this; } @@ -387,87 +386,87 @@ Query.prototype.compVal = function (vals, comp) { return this; }; -Query.prototype.and = function() { +Query.prototype.and = function () { this.options.or = false; return this; }; -Query.prototype.or = function() { +Query.prototype.or = function () { this.options.or = true; return this; }; -Query.prototype.not = function() { +Query.prototype.not = function () { this.notState = true; return this; }; -Query.prototype.null = function() { - if(this.notState) { +Query.prototype.null = function () { + if (this.notState) { return this.compVal(null, 'NOT_NULL'); - } else { - return this.compVal(null, 'NULL'); } + return this.compVal(null, 'NULL'); + }; Query.prototype.eq = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'NE'); - } else { - return this.compVal([val], 'EQ'); } + return this.compVal([val], 'EQ'); + }; Query.prototype.lt = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'GE'); - } else { - return this.compVal([val], 'LT'); } + return this.compVal([val], 'LT'); + }; Query.prototype.le = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'GT'); - } else { - return this.compVal([val], 'LE'); } + return this.compVal([val], 'LE'); + }; Query.prototype.ge = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'LT'); - } else { - return this.compVal([val], 'GE'); } + return this.compVal([val], 'GE'); + }; Query.prototype.gt = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'LE'); - } else { - return this.compVal([val], 'GT'); } + return this.compVal([val], 'GT'); + }; Query.prototype.contains = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'NOT_CONTAINS'); - } else { - return this.compVal([val], 'CONTAINS'); } + return this.compVal([val], 'CONTAINS'); + }; Query.prototype.beginsWith = function (val) { if (this.validationError) { return this; } - if(this.notState) { - this.validationError = new errors.QueryError('Invalid Query state: beginsWith() cannot follow not()'); + if (this.notState) { + this.validationError = new errors.QueryError('Invalid Query state: beginsWith() cannot follow not()'); return this; } return this.compVal([val], 'BEGINS_WITH'); @@ -477,7 +476,7 @@ Query.prototype.in = function (vals) { if (this.validationError) { return this; } - if(this.notState) { + if (this.notState) { this.validationError = new errors.QueryError('Invalid Query state: in() cannot follow not()'); return this; } @@ -489,7 +488,7 @@ Query.prototype.between = function (a, b) { if (this.validationError) { return this; } - if(this.notState) { + if (this.notState) { this.validationError = new errors.QueryError('Invalid Query state: between() cannot follow not()'); return this; } @@ -554,7 +553,7 @@ Query.prototype.using = function (indexName) { Query.prototype.all = function (delay, max) { delay = delay || 1000; max = max || 0; - this.options.all = {'delay': delay, 'max': max}; + this.options.all = {delay, max}; return this; }; diff --git a/lib/Scan.js b/lib/Scan.js index f57c4b8ff..f55723ab1 100644 --- a/lib/Scan.js +++ b/lib/Scan.js @@ -22,8 +22,8 @@ function Scan (Model, filter, options) { this.validationError = null; if (typeof filter === 'string') { this.buildState = filter; - this.filters[filter] = {name: filter}; - } else if (typeof filter === 'object'){ + this.filters[filter] = {'name': filter}; + } else if (typeof filter === 'object') { if (typeof filter.FilterExpression === 'string') { // if filter expression is given, just assign the filter this.filters = filter; @@ -31,15 +31,14 @@ function Scan (Model, filter, options) { this.parseFilterObject(filter); } } - Model._emit('model:scan', 'scan:called', {event: {scan: this}}); + Model._emit('model:scan', 'scan:called', {'event': {'scan': this}}); } - Scan.prototype.exec = async function (next) { debug('exec scan for ', this.scan); - var theScan = this; - this.Model._emit('model:scan', 'exec:start', {event: {scan: this, callback: next}, actions: {updateCallback: function(fn) {next = fn;}}}); + const theScan = this; + this.Model._emit('model:scan', 'exec:start', {'event': {'scan': this, 'callback': next}, 'actions': {'updateCallback' (fn) { next = fn; }}}); if (this.validationError) { if (next) { next(this.validationError); @@ -50,14 +49,14 @@ Scan.prototype.exec = async function (next) { const Model = this.Model; const Model$ = Model.$__; const schema = Model$.schema; - let options = this.options; + const options = this.options; const deferredMain = Q.defer(); let scanReq = { }; async function toModel (item) { - let model = new Model(); + const model = new Model(); model.$__.isNew = false; await schema.parseDynamo(model, item); @@ -66,42 +65,42 @@ Scan.prototype.exec = async function (next) { return model; } - function scanByRawFilter() { + function scanByRawFilter () { const deferred = Q.defer(); - let dbClient = Model.$__.base.documentClient(); - let DynamoDBSet = dbClient.createSet([1, 2, 3]).constructor; + const dbClient = Model.$__.base.documentClient(); + const DynamoDBSet = dbClient.createSet([1, 2, 3]).constructor; - dbClient.scan(scanReq, function(err, data) { + dbClient.scan(scanReq, (err, data) => { if (err) { return deferred.reject(err); - } else { - if (!data) { - return deferred.resolve([]); - } - if (!data.Items) { - let counts = { count: data.Count, scannedCount: data.ScannedCount }; - return deferred.resolve(counts); - } - let returnItems = data.Items.map(function (item) { - let model; - - Object.keys(item).forEach(function (prop) { - if (item[prop] instanceof DynamoDBSet) { - item[prop] = item[prop].values; - } - }); - - model = new Model(item); - model.$__.isNew = false; - debug('scan parsed model', model); - return model; - }).filter(item => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())); - - returnItems.lastKey = data.LastEvaluatedKey; - returnItems.count = data.Count; - returnItems.scannedCount = data.ScannedCount; - return deferred.resolve(returnItems); } + if (!data) { + return deferred.resolve([]); + } + if (!data.Items) { + const counts = {'count': data.Count, 'scannedCount': data.ScannedCount}; + return deferred.resolve(counts); + } + const returnItems = data.Items.map((item) => { + let model; + + Object.keys(item).forEach((prop) => { + if (item[prop] instanceof DynamoDBSet) { + item[prop] = item[prop].values; + } + }); + + model = new Model(item); + model.$__.isNew = false; + debug('scan parsed model', model); + return model; + }).filter((item) => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())); + + returnItems.lastKey = data.LastEvaluatedKey; + returnItems.count = data.Count; + returnItems.scannedCount = data.ScannedCount; + return deferred.resolve(returnItems); + }); return deferred.promise.nodeify(next); @@ -120,83 +119,82 @@ Scan.prototype.exec = async function (next) { // use the document client in aws-sdk return scanByRawFilter(); - } else { - // default - scanReq = { - TableName: Model.$__.name - }; - - if(Object.keys(this.filters).length > 0) { - scanReq.ScanFilter = {}; - for(const name in this.filters) { - const filter = this.filters[name]; - const filterAttr = schema.attributes[name]; - scanReq.ScanFilter[name] = { - AttributeValueList: [], - ComparisonOperator: filter.comparison - }; - - const isContains = filter.comparison === 'CONTAINS' || filter.comparison === 'NOT_CONTAINS'; - const isListContains = isContains && filterAttr.type.name === 'list'; - - if(filter.values) { - for (let i = 0; i < filter.values.length; i += 1) { - const val = filter.values[i]; - scanReq.ScanFilter[name].AttributeValueList.push( - isListContains ? await filterAttr.attributes[0].toDynamo(val, true, Model, {updateTimestamps: false}) : await filterAttr.toDynamo(val, true, Model, {updateTimestamps: false}) - ); - } + } + // default + scanReq = { + 'TableName': Model.$__.name + }; + + if (Object.keys(this.filters).length > 0) { + scanReq.ScanFilter = {}; + for (const name in this.filters) { + const filter = this.filters[name]; + const filterAttr = schema.attributes[name]; + scanReq.ScanFilter[name] = { + 'AttributeValueList': [], + 'ComparisonOperator': filter.comparison + }; + + const isContains = filter.comparison === 'CONTAINS' || filter.comparison === 'NOT_CONTAINS'; + const isListContains = isContains && filterAttr.type.name === 'list'; + + if (filter.values) { + for (let i = 0; i < filter.values.length; i += 1) { + const val = filter.values[i]; + scanReq.ScanFilter[name].AttributeValueList.push( + isListContains ? await filterAttr.attributes[0].toDynamo(val, true, Model, {'updateTimestamps': false}) : await filterAttr.toDynamo(val, true, Model, {'updateTimestamps': false}) + ); } } } + } - if(options.attributes) { - scanReq.AttributesToGet = options.attributes; - } - - if(options.count) { - scanReq.Select = 'COUNT'; - } + if (options.attributes) { + scanReq.AttributesToGet = options.attributes; + } - if(options.counts) { - scanReq.Select = 'COUNT'; - } + if (options.count) { + scanReq.Select = 'COUNT'; + } - if(options.limit) { - scanReq.Limit = options.limit; - } + if (options.counts) { + scanReq.Select = 'COUNT'; + } - if(options.parallel) { - scanReq.TotalSegments = options.parallel; - } + if (options.limit) { + scanReq.Limit = options.limit; + } - if(Array.isArray(options.ExclusiveStartKey)) { - scanReq.TotalSegments = options.ExclusiveStartKey.length; - } else if(options.ExclusiveStartKey) { - options.ExclusiveStartKey = [options.ExclusiveStartKey]; - } + if (options.parallel) { + scanReq.TotalSegments = options.parallel; + } + if (Array.isArray(options.ExclusiveStartKey)) { + scanReq.TotalSegments = options.ExclusiveStartKey.length; + } else if (options.ExclusiveStartKey) { + options.ExclusiveStartKey = [options.ExclusiveStartKey]; + } - if(options.conditionalOperator) { - scanReq.ConditionalOperator = options.conditionalOperator; - } - if(options.consistent) { - scanReq.ConsistentRead = true; - } + if (options.conditionalOperator) { + scanReq.ConditionalOperator = options.conditionalOperator; + } + if (options.consistent) { + scanReq.ConsistentRead = true; } + function scanSegment (segment) { const deferred = Q.defer(); let scanOneReq = {...scanReq}; - if(scanOneReq.TotalSegments) { + if (scanOneReq.TotalSegments) { scanOneReq.Segment = segment; } - if(options.ExclusiveStartKey) { + if (options.ExclusiveStartKey) { scanOneReq.ExclusiveStartKey = options.ExclusiveStartKey[segment]; } @@ -207,20 +205,20 @@ Scan.prototype.exec = async function (next) { options.all = {'delay': 0, 'max': 1}; } scanOne(); - async function scanOne() { + async function scanOne () { debug('scan request', scanOneReq); - let shouldContinue = await theScan.Model._emit('model:scan', 'request:pre', {event: {scan: theScan, callback: next, scanReq: scanOneReq}, actions: {updateScanReq: function(req) {scanOneReq = req;}}}, deferredMain); + const shouldContinue = await theScan.Model._emit('model:scan', 'request:pre', {'event': {'scan': theScan, 'callback': next, 'scanReq': scanOneReq}, 'actions': {'updateScanReq' (req) { scanOneReq = req; }}}, deferredMain); if (shouldContinue === false) { return; } - theScan.Model.$__.base.ddb().scan(scanOneReq, async function(err, data) { - let shouldContinue = await Model._emit('model:scan', 'request:post', {event: {scan: theScan, callback: next, data: data, error: err}, actions: {updateError: function(error) {err = error;}, updateData: function(myData) {data = myData;}}}, deferredMain); + theScan.Model.$__.base.ddb().scan(scanOneReq, async (err, data) => { + const shouldContinue = await Model._emit('model:scan', 'request:post', {'event': {'scan': theScan, 'callback': next, data, 'error': err}, 'actions': {'updateError' (error) { err = error; }, 'updateData' (myData) { data = myData; }}}, deferredMain); if (shouldContinue === false) { return; } - if(err) { + if (err) { debug('Error returned by scan', err); return deferred.reject(err); } debug('scan response', data); - if(!Object.keys(data).length) { + if (!Object.keys(data).length) { return deferred.resolve(); } @@ -229,7 +227,7 @@ Scan.prototype.exec = async function (next) { return deferred.resolve(data.Count); } if (options.counts) { - const counts = { count: data.Count, scannedCount: data.ScannedCount }; + const counts = {'count': data.Count, 'scannedCount': data.ScannedCount}; return deferred.resolve(counts); } if (data.Items !== undefined) { @@ -239,11 +237,11 @@ Scan.prototype.exec = async function (next) { models = models.concat(await Promise.all(data.Items.map(toModel))); } - if(options.one) { + if (options.one) { if (!models || models.length === 0) { return deferred.resolve(); } - return deferred.resolve(models.filter(item => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date()))[0]); + return deferred.resolve(models.filter((item) => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date()))[0]); } lastKey = data.LastEvaluatedKey; } @@ -255,9 +253,8 @@ Scan.prototype.exec = async function (next) { // scan.all need to scan again scanOneReq.ExclusiveStartKey = lastKey; setTimeout(scanOne, options.all.delay); - } - else { - models = models.filter(item => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())); + } else { + models = models.filter((item) => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())); // completed scan returning models models.lastKey = lastKey; @@ -278,38 +275,30 @@ Scan.prototype.exec = async function (next) { function scan () { const totalSegments = scanReq.TotalSegments || 1; - let scans = []; - for(let segment = 0; segment < totalSegments; segment += 1) { + const scans = []; + for (let segment = 0; segment < totalSegments; segment += 1) { scans.push(scanSegment(segment)); } Q.all(scans) - .then(function (results) { + .then((results) => { let models = results.reduce((a, b) => a.concat(b), []); - models = models.filter(item => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())); - let lastKeys = results.map(function (r) { - return r.lastKey; - }); + models = models.filter((item) => !(schema.expires && schema.expires.returnExpiredItems === false && item[schema.expires.attribute] && item[schema.expires.attribute] < new Date())); + const lastKeys = results.map((r) => r.lastKey); - if(lastKeys.length === 1) { + if (lastKeys.length === 1) { models.lastKey = lastKeys[0]; - } else if (lastKeys.filter(v => v).length !== 0){ + } else if (lastKeys.filter((v) => v).length !== 0) { models.lastKey = lastKeys; } - models.count = results.reduce(function(acc, r) { - return acc + r.count; - }, 0); - models.scannedCount = results.reduce(function(acc, r) { - return acc + r.scannedCount; - }, 0); - models.timesScanned = results.reduce(function(acc, r) { - return acc + r.timesScanned; - }, 0); + models.count = results.reduce((acc, r) => acc + r.count, 0); + models.scannedCount = results.reduce((acc, r) => acc + r.scannedCount, 0); + models.timesScanned = results.reduce((acc, r) => acc + r.timesScanned, 0); deferredMain.resolve(models); }) - .fail(function (err) { + .fail((err) => { deferredMain.reject(err); }); @@ -317,8 +306,8 @@ Scan.prototype.exec = async function (next) { } - if(Model$.options.waitForActive) { - return Model$.table.waitForActive().then(scan).catch(function (err) { + if (Model$.options.waitForActive) { + return Model$.table.waitForActive().then(scan).catch((err) => { if (next) { next(err); } @@ -333,14 +322,14 @@ Scan.prototype.parseFilterObject = function (filter) { if (Object.keys(filter).length > 0) { - for(const filterName in filter) { + for (const filterName in filter) { if (filter.hasOwnProperty(filterName)) { // Parse AND OR if (filterName === 'and' || filterName === 'or') { this[filterName](); - for(const condition in filter[filterName]) { + for (const condition in filter[filterName]) { if (filter[filterName].hasOwnProperty(condition)) { this.parseFilterObject(filter[filterName][condition]); } @@ -350,7 +339,7 @@ Scan.prototype.parseFilterObject = function (filter) { this.where(filterName); let val, comp; - if (typeof filter[filterName] === 'object' && Object.keys(filter[filterName]).length === 1) { + if (typeof filter[filterName] === 'object' && Object.keys(filter[filterName]).length === 1) { comp = Object.keys(filter[filterName])[0]; @@ -378,17 +367,17 @@ Scan.prototype.parseFilterObject = function (filter) { } }; -Scan.prototype.and = function() { +Scan.prototype.and = function () { this.options.conditionalOperator = 'AND'; return this; }; -Scan.prototype.or = function() { +Scan.prototype.or = function () { this.options.conditionalOperator = 'OR'; return this; }; -Scan.prototype.consistent = function() { +Scan.prototype.consistent = function () { this.options.consistent = true; return this; }; @@ -398,17 +387,17 @@ Scan.prototype.where = function (filter) { return this; } - if(this.buildState) { + if (this.buildState) { this.validationError = new errors.ScanError('Invalid scan state; where() must follow comparison'); return this; } - if(typeof filter === 'string') { + if (typeof filter === 'string') { this.buildState = filter; - if(this.filters[filter]) { + if (this.filters[filter]) { this.validationError = new errors.ScanError('Invalid scan state; %s can only be used once', filter); return this; } - this.filters[filter] = {name: filter}; + this.filters[filter] = {'name': filter}; } return this; @@ -422,12 +411,12 @@ Scan.prototype.compVal = function (vals, comp) { const permittedComparison = [ - 'NOT_NULL','NULL','EQ','NE','GE','LT','GT','LE','GE', - 'NOT_CONTAINS','CONTAINS','BEGINS_WITH','IN','BETWEEN' + 'NOT_NULL', 'NULL', 'EQ', 'NE', 'GE', 'LT', 'GT', 'LE', 'GE', + 'NOT_CONTAINS', 'CONTAINS', 'BEGINS_WITH', 'IN', 'BETWEEN' ]; - if(!this.buildState) { + if (!this.buildState) { this.validationError = new errors.ScanError('Invalid scan state; %s must follow scan(), where(), or filter()', comp); return this; } @@ -447,78 +436,78 @@ Scan.prototype.compVal = function (vals, comp) { }; -Scan.prototype.not = function() { +Scan.prototype.not = function () { this.notState = true; return this; }; -Scan.prototype.null = function() { - if(this.notState) { +Scan.prototype.null = function () { + if (this.notState) { return this.compVal(null, 'NOT_NULL'); - } else { - return this.compVal(null, 'NULL'); } + return this.compVal(null, 'NULL'); + }; Scan.prototype.eq = function (val) { - if(val === '' || val === null || val === undefined){ + if (val === '' || val === null || val === undefined) { return this.null(); } - if(this.notState) { + if (this.notState) { return this.compVal([val], 'NE'); - } else { - return this.compVal([val], 'EQ'); } + return this.compVal([val], 'EQ'); + }; Scan.prototype.lt = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'GE'); - } else { - return this.compVal([val], 'LT'); } + return this.compVal([val], 'LT'); + }; Scan.prototype.le = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'GT'); - } else { - return this.compVal([val], 'LE'); } + return this.compVal([val], 'LE'); + }; Scan.prototype.ge = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'LT'); - } else { - return this.compVal([val], 'GE'); } + return this.compVal([val], 'GE'); + }; Scan.prototype.gt = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'LE'); - } else { - return this.compVal([val], 'GT'); } + return this.compVal([val], 'GT'); + }; Scan.prototype.contains = function (val) { - if(this.notState) { + if (this.notState) { return this.compVal([val], 'NOT_CONTAINS'); - } else { - return this.compVal([val], 'CONTAINS'); } + return this.compVal([val], 'CONTAINS'); + }; Scan.prototype.beginsWith = function (val) { if (this.validationError) { return this; } - if(this.notState) { + if (this.notState) { this.validationError = new errors.ScanError('Invalid scan state: beginsWith() cannot follow not()'); return this; } @@ -529,7 +518,7 @@ Scan.prototype.in = function (vals) { if (this.validationError) { return this; } - if(this.notState) { + if (this.notState) { this.validationError = new errors.ScanError('Invalid scan state: in() cannot follow not()'); return this; } @@ -541,7 +530,7 @@ Scan.prototype.between = function (a, b) { if (this.validationError) { return this; } - if(this.notState) { + if (this.notState) { this.validationError = new errors.ScanError('Invalid scan state: between() cannot follow not()'); return this; } @@ -578,7 +567,7 @@ Scan.prototype.counts = function () { Scan.prototype.all = function (delay, max) { delay = delay || 1000; max = max || 0; - this.options.all = {'delay': delay, 'max': max}; + this.options.all = {delay, max}; return this; }; diff --git a/lib/Schema.js b/lib/Schema.js index ad45714dc..804eed98c 100644 --- a/lib/Schema.js +++ b/lib/Schema.js @@ -3,12 +3,12 @@ const Attribute = require('./Attribute'); const errors = require('./errors'); const VirtualType = require('./VirtualType'); -//const util = require('util'); +// const util = require('util'); const debug = require('debug')('dynamoose:schema'); -function Schema(obj, options) { +function Schema (obj, options) { debug('Creating Schema', obj); this.tree = {}; @@ -17,19 +17,19 @@ function Schema(obj, options) { this.virtuals = {}; this.options = options || {}; - if(this.options.throughput) { + if (this.options.throughput) { let throughput = this.options.throughput; - if(typeof throughput === 'number') { - throughput = {read: throughput, write: throughput}; + if (typeof throughput === 'number') { + throughput = {'read': throughput, 'write': throughput}; } this.throughput = throughput; } else { - this.throughput = {read: 1, write: 1}; + this.throughput = {'read': 1, 'write': 1}; } - if((!this.throughput.read || !this.throughput.write) && + if ((!this.throughput.read || !this.throughput.write) && this.throughput.read >= 1 && this.throughput.write >= 1) { - throw new errors.SchemaError('Invalid throughput: '+ this.throughput); + throw new errors.SchemaError(`Invalid throughput: ${this.throughput}`); } /* @@ -61,18 +61,18 @@ function Schema(obj, options) { obj[updatedAt] = obj[updatedAt] || {}; obj[updatedAt].type = Date; obj[updatedAt].default = Date.now; - obj[updatedAt].set = function() { return Date.now(); }; - this.timestamps = { createdAt: createdAt, updatedAt: updatedAt }; + obj[updatedAt].set = function () { return Date.now(); }; + this.timestamps = {createdAt, updatedAt}; } /* * Added support for expires attribute */ - if (this.options.expires !== null && this.options.expires !== undefined ) { - let expires = { - attribute: 'expires', - returnExpiredItems: true + if (this.options.expires !== null && this.options.expires !== undefined) { + const expires = { + 'attribute': 'expires', + 'returnExpiredItems': true }; if (typeof this.options.expires === 'number') { @@ -83,7 +83,7 @@ function Schema(obj, options) { } else { throw new errors.SchemaError('Missing or invalided ttl for expires attribute.'); } - if(typeof this.options.expires.attribute === 'string') { + if (typeof this.options.expires.attribute === 'string') { expires.attribute = this.options.expires.attribute; } @@ -98,17 +98,17 @@ function Schema(obj, options) { throw new errors.SchemaError(`Invalid syntax for expires: ${this.options.expires}`); } - let defaultExpires = function () { - return new Date(Date.now() + (expires.ttl * 1000)); + const defaultExpires = function () { + return new Date(Date.now() + expires.ttl * 1000); }; obj[expires.attribute] = { - type: Number, - default: expires.defaultExpires || defaultExpires, - set: function(v) { + 'type': Number, + 'default': expires.defaultExpires || defaultExpires, + 'set' (v) { return Math.floor(v.getTime() / 1000); }, - get: function (v) { + 'get' (v) { return new Date(v * 1000); } }; @@ -120,11 +120,11 @@ function Schema(obj, options) { this.attributeToDynamo = this.options.attributeToDynamo; this.attributes = {}; - this.indexes = {local: {}, global: {}}; + this.indexes = {'local': {}, 'global': {}}; - for(const n in obj) { + for (const n in obj) { - if(this.attributes[n]) { + if (this.attributes[n]) { throw new errors.SchemaError(`Duplicate attribute: ${n}`); } @@ -133,20 +133,20 @@ function Schema(obj, options) { } } -/*Schema.prototype.attribute = function(name, obj) { +/* Schema.prototype.attribute = function(name, obj) { debug('Adding Attribute to Schema (%s)', name, obj); this Attribute.create(name, obj); };*/ -Schema.prototype.toDynamo = async function(model, options) { +Schema.prototype.toDynamo = async function (model, options) { - let dynamoObj = {}; + const dynamoObj = {}; let name, attr; - for(name in model) { - if(!model.hasOwnProperty(name)){ + for (name in model) { + if (!model.hasOwnProperty(name)) { continue; } if (model[name] === undefined || model[name] === null || Number.isNaN(model[name])) { @@ -154,13 +154,13 @@ Schema.prototype.toDynamo = async function(model, options) { continue; } attr = this.attributes[name]; - if((!attr && this.options.saveUnknown === true) || (Array.isArray(this.options.saveUnknown) && this.options.saveUnknown.indexOf(name) >= 0)) { + if (!attr && this.options.saveUnknown === true || Array.isArray(this.options.saveUnknown) && this.options.saveUnknown.indexOf(name) >= 0) { attr = Attribute.create(this, name, model[name]); this.attributes[name] = attr; } } - for(name in this.attributes) { + for (name in this.attributes) { attr = this.attributes[name]; await attr.setDefault(model); @@ -170,35 +170,35 @@ Schema.prototype.toDynamo = async function(model, options) { } else { dynamoAttr = await attr.toDynamo(model[name], undefined, model, options); } - if(dynamoAttr) { + if (dynamoAttr) { dynamoObj[attr.name] = dynamoAttr; } } - debug('toDynamo: %s', dynamoObj ); + debug('toDynamo: %s', dynamoObj); return dynamoObj; }; -Schema.prototype.parseDynamo = async function(model, dynamoObj) { +Schema.prototype.parseDynamo = async function (model, dynamoObj) { - for(const name in dynamoObj) { + for (const name in dynamoObj) { let attr = this.attributes[name]; if (!attr && this.options.errorUnknown) { const hashKey = this.hashKey && this.hashKey.name && dynamoObj[this.hashKey.name] && JSON.stringify(dynamoObj[this.hashKey.name]); const rangeKey = this.rangeKey && this.rangeKey.name && JSON.stringify(dynamoObj[this.rangeKey.name]); let errorMessage = `Unknown top-level attribute ${name} on model ${model.$__.name} with `; - if (hashKey) errorMessage += `hash-key ${hashKey} and `; - if (rangeKey) errorMessage += `range-key ${rangeKey} and `; + if (hashKey) { errorMessage += `hash-key ${hashKey} and `; } + if (rangeKey) { errorMessage += `range-key ${rangeKey} and `; } errorMessage += `value: ${JSON.stringify(dynamoObj[name])}`; throw new errors.ParseError(errorMessage); } - if((!attr && this.options.saveUnknown === true) || (Array.isArray(this.options.saveUnknown) && this.options.saveUnknown.indexOf(name) >= 0)) { + if (!attr && this.options.saveUnknown === true || Array.isArray(this.options.saveUnknown) && this.options.saveUnknown.indexOf(name) >= 0) { attr = Attribute.createUnknownAttributeFromDynamo(this, name, dynamoObj[name]); this.attributes[name] = attr; } - if(attr) { + if (attr) { let attrVal; if (this.attributeFromDynamo) { attrVal = await this.attributeFromDynamo(name, dynamoObj[name], attr.parseDynamo.bind(attr), model); @@ -256,8 +256,8 @@ Schema.prototype.parseDynamo = async function(model, dynamoObj) { */ Schema.prototype.method = function (name, fn) { - if (typeof name !== 'string' ){ - for (const i in name){ + if (typeof name !== 'string') { + for (const i in name) { this.methods[i] = name[i]; } } else { @@ -288,9 +288,9 @@ Schema.prototype.method = function (name, fn) { * @api public */ -Schema.prototype.static = function(name, fn) { - if (typeof name !== 'string' ){ - for (const i in name){ +Schema.prototype.static = function (name, fn) { + if (typeof name !== 'string') { + for (const i in name) { this.statics[i] = name[i]; } } else { @@ -309,11 +309,11 @@ Schema.prototype.static = function(name, fn) { */ Schema.prototype.virtual = function (name, options) { - //let virtuals = this.virtuals; + // let virtuals = this.virtuals; const parts = name.split('.'); - return this.virtuals[name] = parts.reduce(function (mem, part, i) { - mem[part] || (mem[part] = (i === parts.length-1) ? new VirtualType(options, name) : {}); + return this.virtuals[name] = parts.reduce((mem, part, i) => { + mem[part] || (mem[part] = i === parts.length - 1 ? new VirtualType(options, name) : {}); return mem[part]; }, this.tree); }; diff --git a/lib/Table.js b/lib/Table.js index d303c8c36..0eda42e1a 100755 --- a/lib/Table.js +++ b/lib/Table.js @@ -3,7 +3,7 @@ const Q = require('q'); const debug = require('debug')('dynamoose:table'); const deepEqual = require('deep-equal'); -function Table(name, schema, options, base) { +function Table (name, schema, options, base) { debug('new Table (%s)', name, schema); this.name = name; this.schema = schema; @@ -15,18 +15,18 @@ function Table(name, schema, options, base) { } } -const compareIndexes = function compareIndexes(local, remote) { - let indexes = { - delete: [], - create: [] +const compareIndexes = function compareIndexes (local, remote) { + const indexes = { + 'delete': [], + 'create': [] }; - let localTableReq = local; - let remoteTableReq = remote; + const localTableReq = local; + const remoteTableReq = remote; let i; let j; - let localIndexes = localTableReq.GlobalSecondaryIndexes || []; - let remoteIndexes = remoteTableReq.GlobalSecondaryIndexes || []; + const localIndexes = localTableReq.GlobalSecondaryIndexes || []; + const remoteIndexes = remoteTableReq.GlobalSecondaryIndexes || []; debug('compareIndexes'); // let's see what remote indexes we need to sync or create @@ -36,11 +36,11 @@ const compareIndexes = function compareIndexes(local, remote) { if (remoteIndexes[j].IndexName === localIndexes[i].IndexName) { // let's see if the core data matches. if it doesn't, // we may need to delete the remote GSI and rebuild. - let localIndex = (({ IndexName, KeySchema, Projection }) => ({ IndexName, KeySchema, Projection }))(localIndexes[i]); + const localIndex = (({IndexName, KeySchema, Projection}) => ({IndexName, KeySchema, Projection}))(localIndexes[i]); if (Array.isArray(localIndex && localIndex.Projection && localIndex.Projection.NonKeyAttributes)) { localIndex.Projection.NonKeyAttributes.sort(); } - let remoteIndex = (({ IndexName, KeySchema, Projection }) => ({ IndexName, KeySchema, Projection }))(remoteIndexes[j]); + const remoteIndex = (({IndexName, KeySchema, Projection}) => ({IndexName, KeySchema, Projection}))(remoteIndexes[j]); if (Array.isArray(remoteIndex && remoteIndex.Projection && remoteIndex.Projection.NonKeyAttributes)) { remoteIndex.Projection.NonKeyAttributes.sort(); } @@ -79,29 +79,28 @@ const compareIndexes = function compareIndexes(local, remote) { return indexes; }; -Table.prototype.deleteIndex = function deleteIndex(indexName) { +Table.prototype.deleteIndex = function deleteIndex (indexName) { const deferred = Q.defer(); - let table = this; + const table = this; table.active = false; - let params = { - TableName: table.name, - GlobalSecondaryIndexUpdates: [ + const params = { + 'TableName': table.name, + 'GlobalSecondaryIndexUpdates': [ { - Delete: { - IndexName: indexName + 'Delete': { + 'IndexName': indexName } } ] }; - table.base.ddb().updateTable(params, function (err, data) { + table.base.ddb().updateTable(params, (err, data) => { debug('deleteIndex handler running'); if (err) { deferred.reject(err); - } - else { - setTimeout(function () { + } else { + setTimeout(() => { table.waitForActive() - .then(function () { + .then(() => { deferred.resolve(data); }); }, 300); @@ -110,27 +109,26 @@ Table.prototype.deleteIndex = function deleteIndex(indexName) { return deferred.promise; }; -Table.prototype.createIndex = function createIndex(attributes, indexSpec) { +Table.prototype.createIndex = function createIndex (attributes, indexSpec) { const deferred = Q.defer(); - let table = this; + const table = this; table.active = false; - let params = { - TableName: this.name, - AttributeDefinitions: attributes, - GlobalSecondaryIndexUpdates: [ + const params = { + 'TableName': this.name, + 'AttributeDefinitions': attributes, + 'GlobalSecondaryIndexUpdates': [ { - Create: indexSpec + 'Create': indexSpec } ] }; - this.base.ddb().updateTable(params, function (err, data) { + this.base.ddb().updateTable(params, (err, data) => { if (err) { deferred.reject(err); - } - else { - setTimeout(function () { + } else { + setTimeout(() => { table.waitForActive() - .then(function () { + .then(() => { deferred.resolve(data); }); }, 300); @@ -143,64 +141,48 @@ Table.prototype.init = function (next) { debug('initializing table, %s, %j', this.name, this.options); const deferred = Q.defer(); - let table = this; + const table = this; let localTableReq; if (this.options.create) { this.describe() - .then(function (data) { + .then((data) => { debug('table exist -- initialization done'); localTableReq = table.buildTableReq(table.name, table.schema); - let indexes = compareIndexes(localTableReq, data.Table); + const indexes = compareIndexes(localTableReq, data.Table); debug('%s', JSON.stringify(indexes, null, 2)); if (table.options.update) { debug('updating indexes sequentially'); Q() - .then(function() { - return indexes.delete.reduce(function(cur, next) { - return cur.then(function() { return table.deleteIndex(next.IndexName); }); - }, Q()); - }) - .then(function() { - return indexes.create.reduce(function(cur, next) { - return cur.then(function() { return table.createIndex(localTableReq.AttributeDefinitions, next); }); - }, Q()); - }) - .catch(function(e) { debug(e); }); - - } else { - if (indexes.delete.length > 0 || indexes.create.length > 0) { - const mess = `${table.name} indexes are not synchronized and update flag is set to false`; - debug(mess); - deferred.reject(new Error(mess)); - } + .then(() => indexes.delete.reduce((cur, next) => cur.then(() => table.deleteIndex(next.IndexName)), Q())) + .then(() => indexes.create.reduce((cur, next) => cur.then(() => table.createIndex(localTableReq.AttributeDefinitions, next)), Q())) + .catch((e) => { debug(e); }); + + } else if (indexes.delete.length > 0 || indexes.create.length > 0) { + const mess = `${table.name} indexes are not synchronized and update flag is set to false`; + debug(mess); + deferred.reject(new Error(mess)); } table.initialized = true; return table.waitForActive() - .then(function() { - return table.updateTTL(); - }) - .then(function () { - return deferred.resolve(); - }); + .then(() => table.updateTTL()) + .then(() => deferred.resolve()); }) - .catch(function (err) { + .catch((err) => { if (err && err.code === 'ResourceNotFoundException') { debug('table does not exist -- creating'); return deferred.resolve( table.create() - .then(function () { + .then(() => { table.initialized = true; }) - .then(function () { + .then(() => { if (table.options.waitForActive) { return table.waitForActive(); } }) - .then(function () { - return table.updateTTL(); - }) + .then(() => table.updateTTL()) ); } if (err) { @@ -229,11 +211,11 @@ Table.prototype.waitForActive = function (timeout, next) { timeout = this.options.waitForActiveTimeout; } - let table = this; + const table = this; - let timeoutAt = Date.now() + timeout; + const timeoutAt = Date.now() + timeout; - function waitForActive() { + function waitForActive () { debug('Waiting...'); if (Date.now() > timeoutAt) { return deferred.reject( @@ -244,11 +226,11 @@ Table.prototype.waitForActive = function (timeout, next) { return setTimeout(waitForActive, 10); } table.describe() - .then(function (data) { - let active = (data.Table.TableStatus === 'ACTIVE'); - let indexes = data.Table.GlobalSecondaryIndexes || []; - indexes.forEach(function (gsi) { - //debug('waitForActive Index Check: %s', JSON.stringify(gsi, null, 2)); + .then((data) => { + let active = data.Table.TableStatus === 'ACTIVE'; + const indexes = data.Table.GlobalSecondaryIndexes || []; + indexes.forEach((gsi) => { + // debug('waitForActive Index Check: %s', JSON.stringify(gsi, null, 2)); debug('index %s.IndexStatus is %s', gsi.IndexName, gsi.IndexStatus); if (gsi.IndexStatus !== 'ACTIVE') { active = false; @@ -262,7 +244,7 @@ Table.prototype.waitForActive = function (timeout, next) { deferred.resolve(); } }) - .catch(function (err) { + .catch((err) => { if (err && err.code === 'ResourceNotFoundException') { return setTimeout(waitForActive, 10); } @@ -280,12 +262,12 @@ Table.prototype.describeTTL = function (next) { debug('Describing ttl for table, %s', this.name); const deferred = Q.defer(); - let ddb = this.base.ddb(); + const ddb = this.base.ddb(); - let params = { - TableName: this.name + const params = { + 'TableName': this.name }; - ddb.describeTimeToLive(params, function(err, ttlDescription) { + ddb.describeTimeToLive(params, (err, ttlDescription) => { if (err) { return deferred.reject(err); } @@ -300,26 +282,26 @@ Table.prototype.updateTTL = function (next) { debug('Updating ttl for table, %s', this.name); const deferred = Q.defer(); - let table = this; + const table = this; - if(this.schema.expires && !this.base.endpointURL) { + if (this.schema.expires && !this.base.endpointURL) { this.describeTTL() - .then(function (ttlDesc) { - let status = ttlDesc.TimeToLiveDescription.TimeToLiveStatus; - if(status === 'ENABLING' || status === 'ENABLED') { + .then((ttlDesc) => { + const status = ttlDesc.TimeToLiveDescription.TimeToLiveStatus; + if (status === 'ENABLING' || status === 'ENABLED') { return deferred.resolve(); } - let params = { - TableName: table.name, - TimeToLiveSpecification: { - AttributeName: table.schema.expires.attribute, - Enabled: true + const params = { + 'TableName': table.name, + 'TimeToLiveSpecification': { + 'AttributeName': table.schema.expires.attribute, + 'Enabled': true } }; - let ddb = table.base.ddb(); - ddb.updateTimeToLive(params, function(err) { + const ddb = table.base.ddb(); + ddb.updateTimeToLive(params, (err) => { if (err) { return deferred.reject(err); } @@ -334,14 +316,14 @@ Table.prototype.updateTTL = function (next) { }; Table.prototype.describe = function (next) { - let describeTableReq = { - TableName: this.name + const describeTableReq = { + 'TableName': this.name }; - let deferred = Q.defer(); + const deferred = Q.defer(); - let ddb = this.base.ddb(); - ddb.describeTable(describeTableReq, function (err, data) { + const ddb = this.base.ddb(); + ddb.describeTable(describeTableReq, (err, data) => { if (err) { debug('error describing table', err); return deferred.reject(err); @@ -353,12 +335,12 @@ Table.prototype.describe = function (next) { return deferred.promise.nodeify(next); }; -Table.prototype.buildTableReq = function buildTableReq(name, schema) { - let attrDefs = []; +Table.prototype.buildTableReq = function buildTableReq (name, schema) { + const attrDefs = []; - let keyAttr = {}; + const keyAttr = {}; - function addKeyAttr(attr) { + function addKeyAttr (attr) { if (attr) { keyAttr[attr.name] = attr; } @@ -379,27 +361,29 @@ Table.prototype.buildTableReq = function buildTableReq(name, schema) { for (const keyAttrName in keyAttr) { attrDefs.push({ - AttributeName: keyAttrName, - AttributeType: keyAttr[keyAttrName].type.dynamo + 'AttributeName': keyAttrName, + 'AttributeType': keyAttr[keyAttrName].type.dynamo }); } - let keySchema = [{ - AttributeName: schema.hashKey.name, - KeyType: 'HASH' - }]; + const keySchema = [ + { + 'AttributeName': schema.hashKey.name, + 'KeyType': 'HASH' + } + ]; if (schema.rangeKey) { keySchema.push({ - AttributeName: schema.rangeKey.name, - KeyType: 'RANGE' + 'AttributeName': schema.rangeKey.name, + 'KeyType': 'RANGE' }); } - let createTableReq = { - AttributeDefinitions: attrDefs, - TableName: name, - KeySchema: keySchema + const createTableReq = { + 'AttributeDefinitions': attrDefs, + 'TableName': name, + 'KeySchema': keySchema }; if (schema.throughput === 'ON_DEMAND') { @@ -407,9 +391,9 @@ Table.prototype.buildTableReq = function buildTableReq(name, schema) { createTableReq.BillingMode = 'PAY_PER_REQUEST'; } else { debug(`Using PROVISIONED BillingMode for ${name} table creation`); - let provThroughput = { - ReadCapacityUnits: schema.throughput.read, - WriteCapacityUnits: schema.throughput.write + const provThroughput = { + 'ReadCapacityUnits': schema.throughput.read, + 'WriteCapacityUnits': schema.throughput.write }; createTableReq.ProvisionedThroughput = provThroughput; createTableReq.BillingMode = 'PROVISIONED'; @@ -420,33 +404,35 @@ Table.prototype.buildTableReq = function buildTableReq(name, schema) { for (const localSecIndexName in schema.indexes.local) { localSecIndexes = localSecIndexes || []; - let indexAttr = schema.indexes.local[localSecIndexName]; + const indexAttr = schema.indexes.local[localSecIndexName]; index = indexAttr.indexes[localSecIndexName]; - let localSecIndex = { - IndexName: localSecIndexName, - KeySchema: [{ - AttributeName: schema.hashKey.name, - KeyType: 'HASH' - }, { - AttributeName: indexAttr.name, - KeyType: 'RANGE' - }] + const localSecIndex = { + 'IndexName': localSecIndexName, + 'KeySchema': [ + { + 'AttributeName': schema.hashKey.name, + 'KeyType': 'HASH' + }, { + 'AttributeName': indexAttr.name, + 'KeyType': 'RANGE' + } + ] }; if (index.project) { if (Array.isArray(index.project)) { localSecIndex.Projection = { - ProjectionType: 'INCLUDE', - NonKeyAttributes: index.project + 'ProjectionType': 'INCLUDE', + 'NonKeyAttributes': index.project }; } else { localSecIndex.Projection = { - ProjectionType: 'ALL' + 'ProjectionType': 'ALL' }; } } else { localSecIndex.Projection = { - ProjectionType: 'KEYS_ONLY' + 'ProjectionType': 'KEYS_ONLY' }; } @@ -458,46 +444,48 @@ Table.prototype.buildTableReq = function buildTableReq(name, schema) { for (const globalSecIndexName in schema.indexes.global) { globalSecIndexes = globalSecIndexes || []; - let globalIndexAttr = schema.indexes.global[globalSecIndexName]; + const globalIndexAttr = schema.indexes.global[globalSecIndexName]; index = globalIndexAttr.indexes[globalSecIndexName]; - let globalSecIndex = { - IndexName: globalSecIndexName, - KeySchema: [{ - AttributeName: globalIndexAttr.name, - KeyType: 'HASH' - }] + const globalSecIndex = { + 'IndexName': globalSecIndexName, + 'KeySchema': [ + { + 'AttributeName': globalIndexAttr.name, + 'KeyType': 'HASH' + } + ] }; if (createTableReq.BillingMode === 'PROVISIONED') { - let provThroughput = { - ReadCapacityUnits: index.throughput.read, - WriteCapacityUnits: index.throughput.write + const provThroughput = { + 'ReadCapacityUnits': index.throughput.read, + 'WriteCapacityUnits': index.throughput.write }; globalSecIndex.ProvisionedThroughput = provThroughput; } if (index.rangeKey) { globalSecIndex.KeySchema.push({ - AttributeName: index.rangeKey, - KeyType: 'RANGE' + 'AttributeName': index.rangeKey, + 'KeyType': 'RANGE' }); } if (index.project) { if (Array.isArray(index.project)) { globalSecIndex.Projection = { - ProjectionType: 'INCLUDE', - NonKeyAttributes: index.project + 'ProjectionType': 'INCLUDE', + 'NonKeyAttributes': index.project }; } else { globalSecIndex.Projection = { - ProjectionType: 'ALL' + 'ProjectionType': 'ALL' }; } } else { globalSecIndex.Projection = { - ProjectionType: 'KEYS_ONLY' + 'ProjectionType': 'KEYS_ONLY' }; } @@ -515,8 +503,8 @@ Table.prototype.buildTableReq = function buildTableReq(name, schema) { if (this && this.options) { if (this.options.streamOptions && this.options.streamOptions.enabled === true) { createTableReq.StreamSpecification = { - StreamEnabled: true, - StreamViewType: this.options.streamOptions.type + 'StreamEnabled': true, + 'StreamViewType': this.options.streamOptions.type }; } if (this.options.serverSideEncryption) { @@ -530,15 +518,15 @@ Table.prototype.buildTableReq = function buildTableReq(name, schema) { }; Table.prototype.create = function (next) { - let ddb = this.base.ddb(); - let schema = this.schema; - let createTableReq = this.buildTableReq(this.name, schema); + const ddb = this.base.ddb(); + const schema = this.schema; + const createTableReq = this.buildTableReq(this.name, schema); debug('ddb.createTable request:', createTableReq); const deferred = Q.defer(); - ddb.createTable(createTableReq, function (err, data) { + ddb.createTable(createTableReq, (err, data) => { if (err) { debug('error creating table', err); return deferred.reject(err); @@ -551,17 +539,17 @@ Table.prototype.create = function (next) { }; Table.prototype.delete = function (next) { - let deleteTableReq = { - TableName: this.name + const deleteTableReq = { + 'TableName': this.name }; debug('ddb.deleteTable request:', deleteTableReq); - let ddb = this.base.ddb(); + const ddb = this.base.ddb(); const deferred = Q.defer(); - ddb.deleteTable(deleteTableReq, function (err, data) { + ddb.deleteTable(deleteTableReq, (err, data) => { if (err) { debug('error deleting table', err); return deferred.reject(err); diff --git a/lib/VirtualType.js b/lib/VirtualType.js index 56ddfb3d4..12b876882 100644 --- a/lib/VirtualType.js +++ b/lib/VirtualType.js @@ -72,13 +72,13 @@ VirtualType.prototype.set = function (fn) { */ VirtualType.prototype.applyVirtuals = function (model) { debug('applyVirtuals for %s', this.path); - let property = {enumerable: true, configurable: true}; + const property = {'enumerable': true, 'configurable': true}; - if (this.setter){ + if (this.setter) { property.set = this.setter; } - if (this.getter){ + if (this.getter) { property.get = this.getter; } diff --git a/lib/errors.js b/lib/errors.js index 950da6d29..66d680527 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -1,12 +1,12 @@ 'use strict'; const util = require('util'); -function ErrorType(defaultMessage, errorName) { - function newError(message) { - Error.call(this); //super constructor - Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object +function ErrorType (defaultMessage, errorName) { + function newError (message) { + Error.call(this); // super constructor + Error.captureStackTrace(this, this.constructor); // super helper method to include stack trace in error object - this.name = errorName; //set our function’s name as error name. + this.name = errorName; // set our function’s name as error name. this.message = message || defaultMessage; } util.inherits(newError, Error); @@ -14,11 +14,11 @@ function ErrorType(defaultMessage, errorName) { } module.exports = { - SchemaError: new ErrorType('Error with schema', 'SchemaError'), - ModelError: new ErrorType('Error with model', 'ModelError'), - QueryError: new ErrorType('Error with query', 'QueryError'), - ScanError: new ErrorType('Error with scan', 'ScanError'), - TransactionError: new ErrorType('Error with transaction', 'TransactionError'), - ValidationError: new ErrorType('Validation error', 'ValidationError'), - ParseError: new ErrorType('Parse error', 'ParseError') + 'SchemaError': new ErrorType('Error with schema', 'SchemaError'), + 'ModelError': new ErrorType('Error with model', 'ModelError'), + 'QueryError': new ErrorType('Error with query', 'QueryError'), + 'ScanError': new ErrorType('Error with scan', 'ScanError'), + 'TransactionError': new ErrorType('Error with transaction', 'TransactionError'), + 'ValidationError': new ErrorType('Validation error', 'ValidationError'), + 'ParseError': new ErrorType('Parse error', 'ParseError') }; diff --git a/lib/index.js b/lib/index.js index cd85276d9..4df8972bd 100644 --- a/lib/index.js +++ b/lib/index.js @@ -9,9 +9,9 @@ const debugTransaction = require('debug')('dynamoose:transaction'); const Q = require('q'); const errors = require('./errors'); -function createLocalDb(endpointURL) { +function createLocalDb (endpointURL) { return new AWS.DynamoDB({ - endpoint: new AWS.Endpoint(endpointURL) + 'endpoint': new AWS.Endpoint(endpointURL) }); } @@ -19,26 +19,26 @@ function Dynamoose () { this.models = {}; this.defaults = { - create: true, - waitForActive: true, // Wait for table to be created - waitForActiveTimeout: 180000, // 3 minutes - prefix: '', // prefix_Table - suffix: '' // Table_suffix + 'create': true, + 'waitForActive': true, // Wait for table to be created + 'waitForActiveTimeout': 180000, // 3 minutes + 'prefix': '', // prefix_Table + 'suffix': '' // Table_suffix }; // defaults } -Dynamoose.prototype.model = function(name, schema, options) { +Dynamoose.prototype.model = function (name, schema, options) { options = options || {}; - for(const key in this.defaults) { - options[key] = (typeof options[key] === 'undefined') ? this.defaults[key] : options[key]; + for (const key in this.defaults) { + options[key] = typeof options[key] === 'undefined' ? this.defaults[key] : options[key]; } name = options.prefix + name + options.suffix; debug('Looking up model %s', name); - if(this.models[name]) { + if (this.models[name]) { return this.models[name]; } if (!(schema instanceof Schema)) { @@ -69,13 +69,13 @@ Dynamoose.prototype.local = function (url) { /** * Document client for executing nested scans */ -Dynamoose.prototype.documentClient = function() { +Dynamoose.prototype.documentClient = function () { if (this.dynamoDocumentClient) { return this.dynamoDocumentClient; } if (this.endpointURL) { debug('Setting dynamodb document client to %s', this.endpointURL); - this.AWS.config.update({ endpoint: this.endpointURL }); + this.AWS.config.update({'endpoint': this.endpointURL}); } else { debug('Getting default dynamodb document client'); } @@ -83,26 +83,26 @@ Dynamoose.prototype.documentClient = function() { return this.dynamoDocumentClient; }; -Dynamoose.prototype.setDocumentClient = function(documentClient) { +Dynamoose.prototype.setDocumentClient = function (documentClient) { debug('Setting dynamodb document client'); this.dynamoDocumentClient = documentClient; }; Dynamoose.prototype.ddb = function () { - if(this.dynamoDB) { + if (this.dynamoDB) { return this.dynamoDB; } - if(this.endpointURL) { + if (this.endpointURL) { debug('Setting DynamoDB to %s', this.endpointURL); this.dynamoDB = createLocalDb(this.endpointURL); } else { debug('Getting default DynamoDB'); this.dynamoDB = new this.AWS.DynamoDB({ - httpOptions: { - agent: new https.Agent({ - rejectUnauthorized: true, - keepAlive: true + 'httpOptions': { + 'agent': new https.Agent({ + 'rejectUnauthorized': true, + 'keepAlive': true }) } }); @@ -111,8 +111,8 @@ Dynamoose.prototype.ddb = function () { }; Dynamoose.prototype.setDefaults = function (options) { - for(const key in this.defaults) { - options[key] = (typeof options[key] === 'undefined') ? this.defaults[key] : options[key]; + for (const key in this.defaults) { + options[key] = typeof options[key] === 'undefined' ? this.defaults[key] : options[key]; } this.defaults = options; @@ -131,28 +131,28 @@ Dynamoose.prototype.revertDDB = function () { this.dynamoDB = null; }; -Dynamoose.prototype.transaction = async function(items, options, next) { +Dynamoose.prototype.transaction = async function (items, options, next) { debugTransaction('Run Transaction'); const deferred = Q.defer(); - let dbClient = this.documentClient(); - let DynamoDBSet = dbClient.createSet([1, 2, 3]).constructor; - let self = this; + const dbClient = this.documentClient(); + const DynamoDBSet = dbClient.createSet([1, 2, 3]).constructor; + const self = this; options = options || {}; - if(typeof options === 'function') { + if (typeof options === 'function') { next = options; options = {}; } - if(!Array.isArray(items) || items.length === 0) { + if (!Array.isArray(items) || items.length === 0) { deferred.reject(new errors.TransactionError('Items required to run transaction')); return deferred.promise.nodeify(next); } items = await Promise.all(items); - let transactionReq = { - TransactItems: items + const transactionReq = { + 'TransactItems': items }; let transactionMethodName; if (options.type) { @@ -167,11 +167,11 @@ Dynamoose.prototype.transaction = async function(items, options, next) { } } else { debugTransaction('Using predetermined transaction method'); - transactionMethodName = items.map(obj => Object.keys(obj)[0]).every(key => key === 'Get') ? 'transactGetItems' : 'transactWriteItems'; + transactionMethodName = items.map((obj) => Object.keys(obj)[0]).every((key) => key === 'Get') ? 'transactGetItems' : 'transactWriteItems'; } debugTransaction(`Using transaction method: ${transactionMethodName}`); - function getModelSchemaFromIndex(index) { + function getModelSchemaFromIndex (index) { const requestItem = items[index]; const requestItemProperty = Object.keys(items[index])[0]; const tableName = requestItem[requestItemProperty].TableName; @@ -188,27 +188,27 @@ Dynamoose.prototype.transaction = async function(items, options, next) { const transact = () => { debugTransaction('transact', transactionReq); - this.dynamoDB[transactionMethodName](transactionReq, async function(err, data) { - if(err) { + this.dynamoDB[transactionMethodName](transactionReq, async (err, data) => { + if (err) { debugTransaction(`Error returned by ${transactionMethodName}`, err); return deferred.reject(err); } debugTransaction(`${transactionMethodName} response`, data); - if(!data.Responses) { + if (!data.Responses) { return deferred.resolve(); } - return deferred.resolve((await Promise.all(data.Responses.map(async function (item, index) { + return deferred.resolve((await Promise.all(data.Responses.map(async (item, index) => { const {TheModel, schema} = getModelSchemaFromIndex(index); - Object.keys(item).forEach(function (prop) { + Object.keys(item).forEach((prop) => { if (item[prop] instanceof DynamoDBSet) { item[prop] = item[prop].values; } }); - let model = new TheModel(); + const model = new TheModel(); model.$__.isNew = false; // Destruct 'item' DynamoDB's returned structure. await schema.parseDynamo(model, item.Item); diff --git a/lib/reserved-keywords.js b/lib/reserved-keywords.js index f92fa81d9..d2e588d21 100644 --- a/lib/reserved-keywords.js +++ b/lib/reserved-keywords.js @@ -576,7 +576,7 @@ const RESERVED_KEYWORDS_LIST = [ 'ZONE' ]; -const RESERVED_KEYWORDS = exports.RESRVED_KEYWORDS = RESERVED_KEYWORDS_LIST.reduce(function (hash, keyword) { +const RESERVED_KEYWORDS = exports.RESRVED_KEYWORDS = RESERVED_KEYWORDS_LIST.reduce((hash, keyword) => { hash[keyword.toUpperCase()] = true; return hash; }, {}); @@ -586,5 +586,5 @@ exports.isReservedKeyword = function (keyword) { return false; } - return !!RESERVED_KEYWORDS[keyword.toUpperCase()]; + return Boolean(RESERVED_KEYWORDS[keyword.toUpperCase()]); }; diff --git a/release.config.js b/release.config.js index 0213e9c09..f0df866c4 100644 --- a/release.config.js +++ b/release.config.js @@ -1,3 +1,3 @@ module.exports = { - plugins: ['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator', ['@semantic-release/changelog', {'changelogTitle': '# Dynamoose Changelog'}], '@semantic-release/npm', '@semantic-release/git'] + 'plugins': ['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator', ['@semantic-release/changelog', {'changelogTitle': '# Dynamoose Changelog'}], '@semantic-release/npm', '@semantic-release/git'] }; diff --git a/test/General.js b/test/General.js index f46430560..c98b5f485 100644 --- a/test/General.js +++ b/test/General.js @@ -2,9 +2,9 @@ const dynamoose = require('../'); dynamoose.AWS.config.update({ - accessKeyId: 'AKID', - secretAccessKey: 'SECRET', - region: 'us-east-1' + 'accessKeyId': 'AKID', + 'secretAccessKey': 'SECRET', + 'region': 'us-east-1' }); dynamoose.local(); diff --git a/test/LocalDB.js b/test/LocalDB.js index 99535873e..b8e94ce50 100755 --- a/test/LocalDB.js +++ b/test/LocalDB.js @@ -1,25 +1,25 @@ 'use strict'; -var dynamoose = require('../'); +const dynamoose = require('../'); dynamoose.AWS.config.update({ - accessKeyId: 'AKID', - secretAccessKey: 'SECRET', - region: 'us-east-1' + 'accessKeyId': 'AKID', + 'secretAccessKey': 'SECRET', + 'region': 'us-east-1' }); -var should = require('should'); +const should = require('should'); -describe('Local DB tests', function () { - afterEach(function() { +describe('Local DB tests', () => { + afterEach(() => { dynamoose.local(); }); - it('Change to local dynamo db', function () { + it('Change to local dynamo db', () => { dynamoose.dynamoDB = undefined; - var dynamoDB = dynamoose.ddb(); + let dynamoDB = dynamoose.ddb(); should.equal(dynamoDB.endpoint.href, 'http://localhost:8000/'); - var expectURL = 'http://localhost:9000/'; + const expectURL = 'http://localhost:9000/'; dynamoose.local(expectURL); dynamoDB = dynamoose.ddb(); diff --git a/test/Model.js b/test/Model.js index 575d9c120..55b777c0a 100644 --- a/test/Model.js +++ b/test/Model.js @@ -1,33 +1,33 @@ 'use strict'; -var dynamoose = require('../'); +const dynamoose = require('../'); dynamoose.AWS.config.update({ - accessKeyId: 'AKID', - secretAccessKey: 'SECRET', - region: 'us-east-1' + 'accessKeyId': 'AKID', + 'secretAccessKey': 'SECRET', + 'region': 'us-east-1' }); dynamoose.local(); -var should = require('should'); -var CatsFixture = require('./fixtures/Cats'); +const should = require('should'); +const CatsFixture = require('./fixtures/Cats'); -var Cats = {}; +let Cats = {}; -var ONE_YEAR = 365*24*60*60; // 1 years in seconds -var NINE_YEARS = 9*ONE_YEAR; // 9 years in seconds +const ONE_YEAR = 365 * 24 * 60 * 60; // 1 years in seconds +const NINE_YEARS = 9 * ONE_YEAR; // 9 years in seconds -describe('Model', function (){ +describe('Model', function () { this.timeout(15000); - before(function(done) { + before(function (done) { this.timeout(12000); - dynamoose.setDefaults({ prefix: 'test-', suffix: '-db' }); + dynamoose.setDefaults({'prefix': 'test-', 'suffix': '-db'}); Cats = CatsFixture(dynamoose); done(); }); - after(function (done) { + after((done) => { delete dynamoose.models['test-Cat-db']; done(); @@ -48,7 +48,7 @@ describe('Model', function (){ Cats.Cat.$__.name.should.eql('test-Cat-db'); Cats.Cat.$__.options.should.have.property('create', true); - var schema = Cats.Cat.$__.schema; + const schema = Cats.Cat.$__.schema; should.exist(schema); @@ -67,38 +67,38 @@ describe('Model', function (){ schema.hashKey.should.equal(schema.attributes.id); // should be same object should.not.exist(schema.rangeKey); - var kitten = new Cats.Cat( + const kitten = new Cats.Cat( { - id: 1, - name: 'Fluffy', - vet:{name:'theVet', address:'12 somewhere'}, - ears:[{name:'left'}, {name:'right'}], - legs: ['front right', 'front left', 'back right', 'back left'], - more: {favorites: {food: 'fish'}}, - array: [{one: '1'}], - validated: 'valid' + 'id': 1, + 'name': 'Fluffy', + 'vet': {'name': 'theVet', 'address': '12 somewhere'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' } ); kitten.id.should.eql(1); kitten.name.should.eql('Fluffy'); - var dynamoObj = await schema.toDynamo(kitten); + const dynamoObj = await schema.toDynamo(kitten); dynamoObj.should.eql({ - ears: { - L: [ - { M: { name: { S: 'left' } } }, - { M: { name: { S: 'right' } } } + 'ears': { + 'L': [ + {'M': {'name': {'S': 'left'}}}, + {'M': {'name': {'S': 'right'}}} ] }, - id: { N: '1' }, - name: { S: 'Fluffy' }, - vet: { M: { address: { S: '12 somewhere' }, name: { S: 'theVet' } } }, - legs: { SS: ['front right', 'front left', 'back right', 'back left']}, - more: { S: '{"favorites":{"food":"fish"}}' }, - array: { S: '[{"one":"1"}]' }, - validated: { S: 'valid' } + 'id': {'N': '1'}, + 'name': {'S': 'Fluffy'}, + 'vet': {'M': {'address': {'S': '12 somewhere'}, 'name': {'S': 'theVet'}}}, + 'legs': {'SS': ['front right', 'front left', 'back right', 'back left']}, + 'more': {'S': '{"favorites":{"food":"fish"}}'}, + 'array': {'S': '[{"one":"1"}]'}, + 'validated': {'S': 'valid'} }); await kitten.save(); @@ -109,11 +109,11 @@ describe('Model', function (){ this.timeout(12000); const Wolf1 = dynamoose.model('Wolf1', new dynamoose.Schema({ - id: Number, - name: { - type: String, - validate: function (val) { - return new Promise(function(resolve) { + 'id': Number, + 'name': { + 'type': String, + 'validate' (val) { + return new Promise((resolve) => { setTimeout(() => resolve(val.length >= 5), 1000); }); } @@ -122,7 +122,7 @@ describe('Model', function (){ let error; try { - await Wolf1.create({id: 1, name: 'Rob'}); + await Wolf1.create({'id': 1, 'name': 'Rob'}); } catch (e) { error = e; } @@ -130,7 +130,7 @@ describe('Model', function (){ error = null; try { - await Wolf1.create({id: 2, name: 'Smith'}); + await Wolf1.create({'id': 2, 'name': 'Smith'}); } catch (e) { error = e; } @@ -140,22 +140,22 @@ describe('Model', function (){ this.timeout(12000); const Wolf2 = dynamoose.model('Wolf2', new dynamoose.Schema({ - id: Number, - name: { - type: String, - validate: { - isAsync: true, - validator: function (val, cb) { + 'id': Number, + 'name': { + 'type': String, + 'validate': { + 'isAsync': true, + 'validator' (val, cb) { setTimeout(() => cb(val.length >= 5), 1000); }, - disableModelParameter: true + 'disableModelParameter': true } } })); let error; try { - await Wolf2.create({id: 1, name: 'Rob'}); + await Wolf2.create({'id': 1, 'name': 'Rob'}); } catch (e) { error = e; } @@ -163,7 +163,7 @@ describe('Model', function (){ error = null; try { - await Wolf2.create({id: 2, name: 'Smith'}); + await Wolf2.create({'id': 2, 'name': 'Smith'}); } catch (e) { error = e; } @@ -173,22 +173,22 @@ describe('Model', function (){ this.timeout(12000); const Wolf12 = dynamoose.model('Wolf12', new dynamoose.Schema({ - id: Number, - name: { - type: String, - validate: { - isAsync: true, - validate: function (val, cb) { + 'id': Number, + 'name': { + 'type': String, + 'validate': { + 'isAsync': true, + 'validate' (val, cb) { setTimeout(() => cb(val.length >= 5), 1000); }, - disableModelParameter: true + 'disableModelParameter': true } } })); let error; try { - await Wolf12.create({id: 1, name: 'Rob'}); + await Wolf12.create({'id': 1, 'name': 'Rob'}); } catch (e) { error = e; } @@ -196,7 +196,7 @@ describe('Model', function (){ error = null; try { - await Wolf12.create({id: 2, name: 'Smith'}); + await Wolf12.create({'id': 2, 'name': 'Smith'}); } catch (e) { error = e; } @@ -206,12 +206,12 @@ describe('Model', function (){ this.timeout(12000); const Wolf3 = dynamoose.model('Wolf3', new dynamoose.Schema({ - id: Number, - name: { - type: String, - set: function (val) { - return new Promise(function(resolve) { - setTimeout(() => resolve(val + 'Hello World'), 1000); + 'id': Number, + 'name': { + 'type': String, + 'set' (val) { + return new Promise((resolve) => { + setTimeout(() => resolve(`${val}Hello World`), 1000); }); } } @@ -219,7 +219,7 @@ describe('Model', function (){ let error, res; try { - await Wolf3.create({id: 1, name: 'Rob'}); + await Wolf3.create({'id': 1, 'name': 'Rob'}); res = await Wolf3.get(1); } catch (e) { error = e; @@ -232,13 +232,13 @@ describe('Model', function (){ this.timeout(12000); const Wolf4 = dynamoose.model('Wolf4', new dynamoose.Schema({ - id: Number, - name: { - type: String, - set: { - isAsync: true, - set: function (val, cb) { - setTimeout(() => cb(val + 'Hello World'), 1000); + 'id': Number, + 'name': { + 'type': String, + 'set': { + 'isAsync': true, + 'set' (val, cb) { + setTimeout(() => cb(`${val}Hello World`), 1000); } } } @@ -246,7 +246,7 @@ describe('Model', function (){ let error, res; try { - await Wolf4.create({id: 1, name: 'Rob'}); + await Wolf4.create({'id': 1, 'name': 'Rob'}); res = await Wolf4.get(1); } catch (e) { error = e; @@ -259,12 +259,12 @@ describe('Model', function (){ this.timeout(12000); const Wolf5 = dynamoose.model('Wolf5', new dynamoose.Schema({ - id: Number, - name: { - type: String, - get: function (val) { - return new Promise(function(resolve) { - setTimeout(() => resolve(val + 'Hello World'), 1000); + 'id': Number, + 'name': { + 'type': String, + 'get' (val) { + return new Promise((resolve) => { + setTimeout(() => resolve(`${val}Hello World`), 1000); }); } } @@ -272,7 +272,7 @@ describe('Model', function (){ let error, res; try { - await Wolf5.create({id: 1, name: 'Rob'}); + await Wolf5.create({'id': 1, 'name': 'Rob'}); res = await Wolf5.get(1); } catch (e) { error = e; @@ -285,13 +285,13 @@ describe('Model', function (){ this.timeout(12000); const Wolf6 = dynamoose.model('Wolf6', new dynamoose.Schema({ - id: Number, - name: { - type: String, - get: { - isAsync: true, - get: function (val, cb) { - setTimeout(() => cb(val + 'Hello World'), 1000); + 'id': Number, + 'name': { + 'type': String, + 'get': { + 'isAsync': true, + 'get' (val, cb) { + setTimeout(() => cb(`${val}Hello World`), 1000); } } } @@ -299,7 +299,7 @@ describe('Model', function (){ let error, res; try { - await Wolf6.create({id: 1, name: 'Rob'}); + await Wolf6.create({'id': 1, 'name': 'Rob'}); res = await Wolf6.get(1); } catch (e) { error = e; @@ -312,11 +312,11 @@ describe('Model', function (){ this.timeout(12000); const Wolf7 = dynamoose.model('Wolf7', new dynamoose.Schema({ - id: Number, - name: { - type: String, - default: function () { - return new Promise(function(resolve) { + 'id': Number, + 'name': { + 'type': String, + 'default' () { + return new Promise((resolve) => { setTimeout(() => resolve('Hello World'), 1000); }); } @@ -325,7 +325,7 @@ describe('Model', function (){ let error, res; try { - await Wolf7.create({id: 1}); + await Wolf7.create({'id': 1}); res = await Wolf7.get(1); } catch (e) { error = e; @@ -338,12 +338,12 @@ describe('Model', function (){ this.timeout(12000); const Wolf8 = dynamoose.model('Wolf8', new dynamoose.Schema({ - id: Number, - name: { - type: String, - toDynamo: function () { - return new Promise(function(resolve) { - setTimeout(() => resolve({S: 'Hello World'}), 1000); + 'id': Number, + 'name': { + 'type': String, + 'toDynamo' () { + return new Promise((resolve) => { + setTimeout(() => resolve({'S': 'Hello World'}), 1000); }); } } @@ -351,7 +351,7 @@ describe('Model', function (){ let error, res; try { - await Wolf8.create({id: 1, name: 'test'}); + await Wolf8.create({'id': 1, 'name': 'test'}); res = await Wolf8.get(1); } catch (e) { error = e; @@ -364,13 +364,13 @@ describe('Model', function (){ this.timeout(12000); const Wolf11 = dynamoose.model('Wolf11', new dynamoose.Schema({ - id: Number, - name: { - type: String, - toDynamo: { - isAsync: true, - toDynamo: function (val, cb) { - setTimeout(() => cb({S: 'Hello World'}), 1000); + 'id': Number, + 'name': { + 'type': String, + 'toDynamo': { + 'isAsync': true, + 'toDynamo' (val, cb) { + setTimeout(() => cb({'S': 'Hello World'}), 1000); } } } @@ -378,7 +378,7 @@ describe('Model', function (){ let error, res; try { - await Wolf11.create({id: 1, name: 'test'}); + await Wolf11.create({'id': 1, 'name': 'test'}); res = await Wolf11.get(1); } catch (e) { error = e; @@ -391,11 +391,11 @@ describe('Model', function (){ this.timeout(12000); const Wolf9 = dynamoose.model('Wolf9', new dynamoose.Schema({ - id: Number, - name: { - type: String, - fromDynamo: function () { - return new Promise(function(resolve) { + 'id': Number, + 'name': { + 'type': String, + 'fromDynamo' () { + return new Promise((resolve) => { setTimeout(() => resolve('Hello World'), 1000); }); } @@ -404,7 +404,7 @@ describe('Model', function (){ let error, res; try { - await Wolf9.create({id: 1, name: 'test'}); + await Wolf9.create({'id': 1, 'name': 'test'}); res = await Wolf9.get(1); } catch (e) { error = e; @@ -417,12 +417,12 @@ describe('Model', function (){ this.timeout(12000); const Wolf10 = dynamoose.model('Wolf10', new dynamoose.Schema({ - id: Number, - name: { - type: String, - fromDynamo: { - isAsync: true, - fromDynamo: function (val, cb) { + 'id': Number, + 'name': { + 'type': String, + 'fromDynamo': { + 'isAsync': true, + 'fromDynamo' (val, cb) { setTimeout(() => cb('Hello World'), 1000); } } @@ -431,7 +431,7 @@ describe('Model', function (){ let error, res; try { - await Wolf10.create({id: 1, name: 'test'}); + await Wolf10.create({'id': 1, 'name': 'test'}); res = await Wolf10.get(1); } catch (e) { error = e; @@ -441,7 +441,7 @@ describe('Model', function (){ res.name.should.eql('Hello World'); }); - it('Create simple model with range key', function () { + it('Create simple model with range key', () => { Cats.Cat2.should.have.property('name'); // Older node doesn't support Function.name changes @@ -454,7 +454,7 @@ describe('Model', function (){ Cats.Cat2.$__.name.should.eql('test-Cat2-db'); Cats.Cat2.$__.options.should.have.property('create', true); - var schema = Cats.Cat2.$__.schema; + const schema = Cats.Cat2.$__.schema; should.exist(schema); @@ -489,7 +489,7 @@ describe('Model', function (){ Cats.Cat5.$__.name.should.eql('test-Cat5-db'); Cats.Cat5.$__.options.should.have.property('saveUnknown', true); - var schema = Cats.Cat5.$__.schema; + const schema = Cats.Cat5.$__.schema; should.exist(schema); @@ -508,69 +508,69 @@ describe('Model', function (){ schema.hashKey.should.equal(schema.attributes.id); // should be same object should.not.exist(schema.rangeKey); - var kitten = new Cats.Cat5( + const kitten = new Cats.Cat5( { - id: 2, - name: 'Fluffy', - owner: 'Someone', - unnamedInt: 1, - unnamedInt0: 0, - unnamedBooleanFalse: false, - unnamedBooleanTrue: true, - unnamedString: 'unnamed', + 'id': 2, + 'name': 'Fluffy', + 'owner': 'Someone', + 'unnamedInt': 1, + 'unnamedInt0': 0, + 'unnamedBooleanFalse': false, + 'unnamedBooleanTrue': true, + 'unnamedString': 'unnamed', // Attributes with empty values. DynamoDB won't store empty values // so the return value of toDynamo() should exclude these attributes. - unnamedUndefined: undefined, - unnamedNull: null, - unnamedEmptyString: '', - unnamedNumberNaN: NaN, + 'unnamedUndefined': undefined, + 'unnamedNull': null, + 'unnamedEmptyString': '', + 'unnamedNumberNaN': NaN } ); kitten.id.should.eql(2); kitten.name.should.eql('Fluffy'); - var dynamoObj = await schema.toDynamo(kitten); + const dynamoObj = await schema.toDynamo(kitten); dynamoObj.should.eql({ - id: { N: '2' }, - name: { S: 'Fluffy' }, - owner: { S: 'Someone' }, - unnamedInt: { N: '1' }, - unnamedInt0: { N: '0' }, - unnamedBooleanFalse: { BOOL: false }, - unnamedBooleanTrue: { BOOL: true }, - unnamedString: { S: 'unnamed' }, + 'id': {'N': '2'}, + 'name': {'S': 'Fluffy'}, + 'owner': {'S': 'Someone'}, + 'unnamedInt': {'N': '1'}, + 'unnamedInt0': {'N': '0'}, + 'unnamedBooleanFalse': {'BOOL': false}, + 'unnamedBooleanTrue': {'BOOL': true}, + 'unnamedString': {'S': 'unnamed'} }); await kitten.save(); }); - it('Create returnRequest option', function (done) { - Cats.ExpiringCat.create({name: 'Leo'}, {returnRequest: true}) - .then(function (request) { + it('Create returnRequest option', (done) => { + Cats.ExpiringCat.create({'name': 'Leo'}, {'returnRequest': true}) + .then((request) => { request.should.exist; request.TableName.should.eql('test-ExpiringCat-db'); - request.Item.name.should.eql({S: 'Leo'}); + request.Item.name.should.eql({'S': 'Leo'}); done(); }) .catch(done); }); - it('Should support useDocumentTypes and useNativeBooleans being false', function(done) { + it('Should support useDocumentTypes and useNativeBooleans being false', function (done) { this.timeout(12000); - var kitten = new Cats.Cat10({ - id: 2, - isHappy: true, - parents: ['Max', 'Leah'], - details: { - playful: true, - thirsty: false, - tired: false + const kitten = new Cats.Cat10({ + 'id': 2, + 'isHappy': true, + 'parents': ['Max', 'Leah'], + 'details': { + 'playful': true, + 'thirsty': false, + 'tired': false } }); @@ -578,29 +578,29 @@ describe('Model', function (){ kitten.isHappy.should.eql(true); kitten.parents.should.eql(['Max', 'Leah']); kitten.details.should.eql({ - playful: true, - thirsty: false, - tired: false + 'playful': true, + 'thirsty': false, + 'tired': false }); - kitten.save(function(err, kitten) { + kitten.save((err, kitten) => { kitten.id.should.eql(2); kitten.isHappy.should.eql(true); kitten.parents.should.eql(['Max', 'Leah']); kitten.details.should.eql({ - playful: true, - thirsty: false, - tired: false + 'playful': true, + 'thirsty': false, + 'tired': false }); - Cats.Cat10.get(2, function(err, kitten) { + Cats.Cat10.get(2, (err, kitten) => { kitten.id.should.eql(2); kitten.isHappy.should.eql(true); kitten.parents.should.eql(['Max', 'Leah']); kitten.details.should.eql({ - playful: true, - thirsty: false, - tired: false + 'playful': true, + 'thirsty': false, + 'tired': false }); done(); @@ -622,7 +622,7 @@ describe('Model', function (){ Cats.Cat1.$__.name.should.eql('test-Cat1-db'); Cats.Cat1.$__.options.should.have.property('saveUnknown', true); - var schema = Cats.Cat1.$__.schema; + const schema = Cats.Cat1.$__.schema; should.exist(schema); @@ -641,50 +641,50 @@ describe('Model', function (){ schema.hashKey.should.equal(schema.attributes.id); // should be same object should.not.exist(schema.rangeKey); - var kitten = new Cats.Cat1( + const kitten = new Cats.Cat1( { - id: 2, - name: 'Fluffy', - owner: 'Someone', - children: { - 'mittens' : { - name : 'mittens', - age: 1 + 'id': 2, + 'name': 'Fluffy', + 'owner': 'Someone', + 'children': { + 'mittens': { + 'name': 'mittens', + 'age': 1 }, - 'puddles' : { - name : 'puddles', - age: 2 + 'puddles': { + 'name': 'puddles', + 'age': 2 } }, - characteristics: ['cute', 'fuzzy'] + 'characteristics': ['cute', 'fuzzy'] } ); kitten.id.should.eql(2); kitten.name.should.eql('Fluffy'); - var dynamoObj = await schema.toDynamo(kitten); + const dynamoObj = await schema.toDynamo(kitten); dynamoObj.should.eql({ - id: {N: '2'}, - name: {S: 'Fluffy'}, - owner: {S: 'Someone'}, - children: { - M: { - 'mittens': {M: {'name': {S: 'mittens'}, 'age': {N: '1'}}}, - 'puddles': {M: {'name': {S: 'puddles'}, 'age': {N: '2'}}} + 'id': {'N': '2'}, + 'name': {'S': 'Fluffy'}, + 'owner': {'S': 'Someone'}, + 'children': { + 'M': { + 'mittens': {'M': {'name': {'S': 'mittens'}, 'age': {'N': '1'}}}, + 'puddles': {'M': {'name': {'S': 'puddles'}, 'age': {'N': '2'}}} } }, - characteristics: {L: [{S: 'cute'}, {S: 'fuzzy'}]} + 'characteristics': {'L': [{'S': 'cute'}, {'S': 'fuzzy'}]} }); await kitten.save(); }); - it('Get item for model with unnamed attributes', function (done) { + it('Get item for model with unnamed attributes', (done) => { - Cats.Cat5.get(2, function(err, model) { + Cats.Cat5.get(2, (err, model) => { should.not.exist(err); should.exist(model); @@ -698,26 +698,24 @@ describe('Model', function (){ }); }); - it('Get item for model', function (done) { + it('Get item for model', (done) => { - Cats.Cat.get(1, function(err, model) { + Cats.Cat.get(1, (err, model) => { should.not.exist(err); should.exist(model); model.should.have.property('id', 1); model.should.have.property('name', 'Fluffy'); - model.should.have.property('vet', { address: '12 somewhere', name: 'theVet' }); + model.should.have.property('vet', {'address': '12 somewhere', 'name': 'theVet'}); model.should.have.property('$__'); done(); }); }); - it('Get item for model with falsy keys', function (done) { - Cats.Cat8.create({id: 0, age: 0}) - .then(function () { - return Cats.Cat8.get({id: 0, age: 0}); - }) - .then(function (falsyCat) { + it('Get item for model with falsy keys', (done) => { + Cats.Cat8.create({'id': 0, 'age': 0}) + .then(() => Cats.Cat8.get({'id': 0, 'age': 0})) + .then((falsyCat) => { falsyCat.should.have.property('id', 0); falsyCat.should.have.property('age', 0); done(); @@ -725,9 +723,9 @@ describe('Model', function (){ .catch(done); }); - it('Get item with invalid key', function (done) { + it('Get item with invalid key', (done) => { - Cats.Cat.get(0, function(err, model) { + Cats.Cat.get(0, (err, model) => { should.exist(err); err.name.should.equal('ValidationError'); should.not.exist(model); @@ -735,49 +733,45 @@ describe('Model', function (){ }); }); - it('Get and Update corrupted item', function (done) { + it('Get and Update corrupted item', (done) => { // create corrupted item - var req = dynamoose.ddb().putItem({ - Item: { + const req = dynamoose.ddb().putItem({ + 'Item': { 'id': { - N: '7' + 'N': '7' }, 'isHappy': { // this is the data corruption - S: 'tue' + 'S': 'tue' } }, - ReturnConsumedCapacity: 'TOTAL', - TableName: Cats.Cat7.$__.table.name + 'ReturnConsumedCapacity': 'TOTAL', + 'TableName': Cats.Cat7.$__.table.name }); - req.promise().then(function(){ - return Cats.Cat7.get(7); - }).catch(function(err){ + req.promise().then(() => Cats.Cat7.get(7)).catch((err) => { should.exist(err.message); - }).then(function(){ - return Cats.Cat7.update(7, { name : 'my favorite cat'}); - }).catch(function(err){ + }).then(() => Cats.Cat7.update(7, {'name': 'my favorite cat'})).catch((err) => { should.exist(err.message); done(); }); }); - it('Get returnRequest option', function (done) { - Cats.Cat.get(1, {returnRequest: true}, function(err, request) { + it('Get returnRequest option', (done) => { + Cats.Cat.get(1, {'returnRequest': true}, (err, request) => { should.not.exist(err); should.exist(request); request.TableName.should.eql('test-Cat-db'); - request.Key.should.eql({id: {N: '1'}}); + request.Key.should.eql({'id': {'N': '1'}}); done(); }); }); - it('Save existing item', function (done) { + it('Save existing item', (done) => { - Cats.Cat.get(1, function(err, model) { + Cats.Cat.get(1, (err, model) => { should.not.exist(err); should.exist(model); @@ -787,10 +781,10 @@ describe('Model', function (){ model.vet.name = 'Tough Vet'; model.ears[0].name = 'right'; - model.save(function (err) { + model.save((err) => { should.not.exist(err); - Cats.Cat.get({id: 1}, {consistent: true}, function(err, badCat) { + Cats.Cat.get({'id': 1}, {'consistent': true}, (err, badCat) => { should.not.exist(err); badCat.name.should.eql('Bad Cat'); badCat.vet.name.should.eql('Tough Vet'); @@ -802,26 +796,26 @@ describe('Model', function (){ }); }); - it('Save existing item without defining updating timestamps', function (done) { - var myCat = new Cats.Cat9({ - id: 1, - name: 'Fluffy', - vet:{name:'theVet', address:'12 somewhere'}, - ears:[{name:'left'}, {name:'right'}], - legs: ['front right', 'front left', 'back right', 'back left'], - more: {favorites: {food: 'fish'}}, - array: [{one: '1'}], - validated: 'valid' + it('Save existing item without defining updating timestamps', (done) => { + const myCat = new Cats.Cat9({ + 'id': 1, + 'name': 'Fluffy', + 'vet': {'name': 'theVet', 'address': '12 somewhere'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }); - myCat.save(function(err, theSavedCat1) { - var expectedCreatedAt = theSavedCat1.createdAt; - var expectedUpdatedAt = theSavedCat1.updatedAt; + myCat.save((err, theSavedCat1) => { + const expectedCreatedAt = theSavedCat1.createdAt; + const expectedUpdatedAt = theSavedCat1.updatedAt; theSavedCat1.name = 'FluffyB'; - setTimeout(function() { - theSavedCat1.save(function () { - Cats.Cat9.get(1, function(err, realCat) { + setTimeout(() => { + theSavedCat1.save(() => { + Cats.Cat9.get(1, (err, realCat) => { realCat.name.should.eql('FluffyB'); realCat.createdAt.should.eql(expectedCreatedAt); // createdAt should be the same as before realCat.updatedAt.should.not.eql(expectedUpdatedAt); // updatedAt should be different than before @@ -832,26 +826,26 @@ describe('Model', function (){ }); }); - it('Save existing item with updating timestamps', function (done) { - var myCat = new Cats.Cat9({ - id: 1, - name: 'Fluffy', - vet:{name:'theVet', address:'12 somewhere'}, - ears:[{name:'left'}, {name:'right'}], - legs: ['front right', 'front left', 'back right', 'back left'], - more: {favorites: {food: 'fish'}}, - array: [{one: '1'}], - validated: 'valid' + it('Save existing item with updating timestamps', (done) => { + const myCat = new Cats.Cat9({ + 'id': 1, + 'name': 'Fluffy', + 'vet': {'name': 'theVet', 'address': '12 somewhere'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }); - myCat.save(function(err, theSavedCat1) { - var expectedCreatedAt = theSavedCat1.createdAt; - var expectedUpdatedAt = theSavedCat1.updatedAt; + myCat.save((err, theSavedCat1) => { + const expectedCreatedAt = theSavedCat1.createdAt; + const expectedUpdatedAt = theSavedCat1.updatedAt; myCat.name = 'FluffyB'; - setTimeout(function() { - myCat.save({updateTimestamps: true}, function () { - Cats.Cat9.get(1, function(err, realCat) { + setTimeout(() => { + myCat.save({'updateTimestamps': true}, () => { + Cats.Cat9.get(1, (err, realCat) => { realCat.name.should.eql('FluffyB'); realCat.createdAt.should.eql(expectedCreatedAt); // createdAt should be the same as before realCat.updatedAt.should.not.eql(expectedUpdatedAt); // updatedAt should be different than before @@ -862,26 +856,26 @@ describe('Model', function (){ }); }); - it('Save existing item without updating timestamps', function (done) { - var myCat = new Cats.Cat9({ - id: 1, - name: 'Fluffy', - vet:{name:'theVet', address:'12 somewhere'}, - ears:[{name:'left'}, {name:'right'}], - legs: ['front right', 'front left', 'back right', 'back left'], - more: {favorites: {food: 'fish'}}, - array: [{one: '1'}], - validated: 'valid' + it('Save existing item without updating timestamps', (done) => { + const myCat = new Cats.Cat9({ + 'id': 1, + 'name': 'Fluffy', + 'vet': {'name': 'theVet', 'address': '12 somewhere'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }); - myCat.save(function(err, theSavedCat1) { - var expectedCreatedAt = theSavedCat1.createdAt; - var expectedUpdatedAt = theSavedCat1.updatedAt; + myCat.save((err, theSavedCat1) => { + const expectedCreatedAt = theSavedCat1.createdAt; + const expectedUpdatedAt = theSavedCat1.updatedAt; myCat.name = 'FluffyB'; - setTimeout(function() { - myCat.save({updateTimestamps: false}, function () { - Cats.Cat9.get(1, function(err, realCat) { + setTimeout(() => { + myCat.save({'updateTimestamps': false}, () => { + Cats.Cat9.get(1, (err, realCat) => { realCat.name.should.eql('FluffyB'); realCat.createdAt.should.eql(expectedCreatedAt); // createdAt should be the same as before realCat.updatedAt.should.eql(expectedUpdatedAt); // updatedAt should be the same as before @@ -893,25 +887,25 @@ describe('Model', function (){ }); - it('Save existing item with updating expires', function (done) { - var myCat = new Cats.Cat11({ - id: 1, - name: 'Fluffy', - vet:{name:'theVet', address:'12 somewhere'}, - ears:[{name:'left'}, {name:'right'}], - legs: ['front right', 'front left', 'back right', 'back left'], - more: {favorites: {food: 'fish'}}, - array: [{one: '1'}], - validated: 'valid' + it('Save existing item with updating expires', (done) => { + const myCat = new Cats.Cat11({ + 'id': 1, + 'name': 'Fluffy', + 'vet': {'name': 'theVet', 'address': '12 somewhere'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }); - myCat.save(function(err, theSavedCat1) { - var expectedExpires = theSavedCat1.expires; + myCat.save((err, theSavedCat1) => { + const expectedExpires = theSavedCat1.expires; myCat.name = 'FluffyB'; - setTimeout(function() { - myCat.save({updateExpires: true}, function () { - Cats.Cat11.get(1, function(err, realCat) { + setTimeout(() => { + myCat.save({'updateExpires': true}, () => { + Cats.Cat11.get(1, (err, realCat) => { realCat.name.should.eql('FluffyB'); realCat.expires.should.not.eql(expectedExpires); // expires should be different than before done(); @@ -922,25 +916,25 @@ describe('Model', function (){ }); - it('Save existing item without updating expires', function (done) { - var myCat = new Cats.Cat11({ - id: 2, - name: 'Fluffy', - vet:{name:'theVet', address:'12 somewhere'}, - ears:[{name:'left'}, {name:'right'}], - legs: ['front right', 'front left', 'back right', 'back left'], - more: {favorites: {food: 'fish'}}, - array: [{one: '1'}], - validated: 'valid' + it('Save existing item without updating expires', (done) => { + const myCat = new Cats.Cat11({ + 'id': 2, + 'name': 'Fluffy', + 'vet': {'name': 'theVet', 'address': '12 somewhere'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }); - myCat.save(function(err, theSavedCat1) { - var expectedExpires = theSavedCat1.expires; + myCat.save((err, theSavedCat1) => { + const expectedExpires = theSavedCat1.expires; myCat.name = 'FluffyB'; - setTimeout(function() { - myCat.save({updateExpires: false}, function () { - Cats.Cat11.get(2, function(err, realCat) { + setTimeout(() => { + myCat.save({'updateExpires': false}, () => { + Cats.Cat11.get(2, (err, realCat) => { realCat.name.should.eql('FluffyB'); realCat.expires.should.eql(expectedExpires); // expires should be the same as before done(); @@ -951,25 +945,25 @@ describe('Model', function (){ }); - it('Save existing item without updating expires (default)', function (done) { - var myCat = new Cats.Cat11({ - id: 3, - name: 'Fluffy', - vet:{name:'theVet', address:'12 somewhere'}, - ears:[{name:'left'}, {name:'right'}], - legs: ['front right', 'front left', 'back right', 'back left'], - more: {favorites: {food: 'fish'}}, - array: [{one: '1'}], - validated: 'valid' + it('Save existing item without updating expires (default)', (done) => { + const myCat = new Cats.Cat11({ + 'id': 3, + 'name': 'Fluffy', + 'vet': {'name': 'theVet', 'address': '12 somewhere'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }); - myCat.save(function(err, theSavedCat1) { - var expectedExpires = theSavedCat1.expires; + myCat.save((err, theSavedCat1) => { + const expectedExpires = theSavedCat1.expires; myCat.name = 'FluffyB'; - setTimeout(function() { - myCat.save(function () { - Cats.Cat11.get(3, function(err, realCat) { + setTimeout(() => { + myCat.save(() => { + Cats.Cat11.get(3, (err, realCat) => { realCat.name.should.eql('FluffyB'); realCat.expires.should.eql(expectedExpires); // expires should be the same as before done(); @@ -979,8 +973,8 @@ describe('Model', function (){ }); }); - it('Save existing item with a false condition', function (done) { - Cats.Cat.get(1, function(err, model) { + it('Save existing item with a false condition', (done) => { + Cats.Cat.get(1, (err, model) => { should.not.exist(err); should.exist(model); @@ -988,14 +982,14 @@ describe('Model', function (){ model.name = 'Whiskers'; model.save({ - condition: '#name = :name', - conditionNames: { name: 'name' }, - conditionValues: { name: 'Muffin' } - }, function (err) { + 'condition': '#name = :name', + 'conditionNames': {'name': 'name'}, + 'conditionValues': {'name': 'Muffin'} + }, (err) => { should.exist(err); err.code.should.eql('ConditionalCheckFailedException'); - Cats.Cat.get({id: 1}, {consistent: true}, function(err, badCat) { + Cats.Cat.get({'id': 1}, {'consistent': true}, (err, badCat) => { should.not.exist(err); badCat.name.should.eql('Bad Cat'); done(); @@ -1004,8 +998,8 @@ describe('Model', function (){ }); }); - it('Save existing item with a true condition', function (done) { - Cats.Cat.get(1, function(err, model) { + it('Save existing item with a true condition', (done) => { + Cats.Cat.get(1, (err, model) => { should.not.exist(err); should.exist(model); @@ -1013,13 +1007,13 @@ describe('Model', function (){ model.name = 'Whiskers'; model.save({ - condition: '#name = :name', - conditionNames: { name: 'name' }, - conditionValues: { name: 'Bad Cat' } - }, function (err) { + 'condition': '#name = :name', + 'conditionNames': {'name': 'name'}, + 'conditionValues': {'name': 'Bad Cat'} + }, (err) => { should.not.exist(err); - Cats.Cat.get({id: 1}, {consistent: true}, function(err, whiskers) { + Cats.Cat.get({'id': 1}, {'consistent': true}, (err, whiskers) => { should.not.exist(err); whiskers.name.should.eql('Whiskers'); done(); @@ -1028,14 +1022,14 @@ describe('Model', function (){ }); }); - it('Save with a pre hook', function (done) { - var flag = false; - Cats.Cat.pre('save', function (next) { + it('Save with a pre hook', (done) => { + let flag = false; + Cats.Cat.pre('save', (next) => { flag = true; next(); }); - Cats.Cat.get(1, function(err, model) { + Cats.Cat.get(1, (err, model) => { should.not.exist(err); should.exist(model); @@ -1043,10 +1037,10 @@ describe('Model', function (){ model.name = 'Fluffy'; model.vet.name = 'Nice Guy'; - model.save(function (err) { + model.save((err) => { should.not.exist(err); - Cats.Cat.get({id: 1}, {consistent: true}, function(err, badCat) { + Cats.Cat.get({'id': 1}, {'consistent': true}, (err, badCat) => { should.not.exist(err); badCat.name.should.eql('Fluffy'); badCat.vet.name.should.eql('Nice Guy'); @@ -1059,16 +1053,16 @@ describe('Model', function (){ }); }); - it('Save existing item with an invalid attribute', function (done) { - Cats.Cat.get(1, function(err, model) { + it('Save existing item with an invalid attribute', (done) => { + Cats.Cat.get(1, (err, model) => { should.not.exist(err); should.exist(model); model.validated = 'bad'; - model.save().catch(function(err) { + model.save().catch((err) => { should.exist(err); err.name.should.equal('ValidationError'); - Cats.Cat.get({id: 1}, {consistent: true}, function(err, badCat) { + Cats.Cat.get({'id': 1}, {'consistent': true}, (err, badCat) => { should.not.exist(err); badCat.name.should.eql('Fluffy'); badCat.vet.name.should.eql('Nice Guy'); @@ -1080,50 +1074,50 @@ describe('Model', function (){ }); }); - it('Deletes item', function (done) { + it('Deletes item', (done) => { - var cat = new Cats.Cat({id: 1}); + const cat = new Cats.Cat({'id': 1}); cat.delete(done); }); - it('Deletes item with invalid key', function (done) { + it('Deletes item with invalid key', (done) => { - var cat = new Cats.Cat({id: 0}); + const cat = new Cats.Cat({'id': 0}); - cat.delete(function(err) { + cat.delete((err) => { should.exist(err); err.name.should.equal('ValidationError'); done(); }); }); - it('Delete returnRequest option', function (done) { - var cat = new Cats.Cat({id: 1}); + it('Delete returnRequest option', (done) => { + const cat = new Cats.Cat({'id': 1}); - cat.delete({returnRequest: true}, function (err, request) { + cat.delete({'returnRequest': true}, (err, request) => { should.not.exist(err); request.should.exist; request.TableName.should.eql('test-Cat-db'); - request.Key.should.eql({id: {N: '1'}}); + request.Key.should.eql({'id': {'N': '1'}}); done(); }); }); - it('Get missing item', function (done) { + it('Get missing item', (done) => { - Cats.Cat.get(1, function(err, model) { + Cats.Cat.get(1, (err, model) => { should.not.exist(err); should.not.exist(model); done(); }); }); - it('Static Creates new item', function (done) { - Cats.Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { + it('Static Creates new item', (done) => { + Cats.Cat.create({'id': 666, 'name': 'Garfield'}, (err, garfield) => { should.not.exist(err); should.exist(garfield); garfield.id.should.eql(666); @@ -1131,8 +1125,8 @@ describe('Model', function (){ }); }); - it('Static Creates new item with range key', function (done) { - Cats.Cat2.create({ownerId: 666, name: 'Garfield'}, function (err, garfield) { + it('Static Creates new item with range key', (done) => { + Cats.Cat2.create({'ownerId': 666, 'name': 'Garfield'}, (err, garfield) => { should.not.exist(err); should.exist(garfield); garfield.ownerId.should.eql(666); @@ -1140,32 +1134,32 @@ describe('Model', function (){ }); }); - it('Prevent duplicate create', function (done) { - Cats.Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { + it('Prevent duplicate create', (done) => { + Cats.Cat.create({'id': 666, 'name': 'Garfield'}, (err, garfield) => { should.exist(err); should.not.exist(garfield); done(); }); }); - it('Should allow for primary key being `_id` while creating', function (done) { - Cats.Cat12.create({_id: 666, name: 'Garfield'}, function (err, garfield) { + it('Should allow for primary key being `_id` while creating', (done) => { + Cats.Cat12.create({'_id': 666, 'name': 'Garfield'}, (err, garfield) => { should.not.exist(err); should.exist(garfield); done(); }); }); - it('Prevent duplicate create with range key', function (done) { - Cats.Cat2.create({ownerId: 666, name: 'Garfield'}, function (err, garfield) { + it('Prevent duplicate create with range key', (done) => { + Cats.Cat2.create({'ownerId': 666, 'name': 'Garfield'}, (err, garfield) => { should.exist(err); should.not.exist(garfield); done(); }); }); - it('Static Creates second item', function (done) { - Cats.Cat.create({id: 777, name: 'Catbert'}, function (err, catbert) { + it('Static Creates second item', (done) => { + Cats.Cat.create({'id': 777, 'name': 'Catbert'}, (err, catbert) => { should.not.exist(err); should.exist(catbert); catbert.id.should.eql(777); @@ -1173,19 +1167,17 @@ describe('Model', function (){ }); }); - it('BatchGet items', function (done) { - Cats.Cat.batchGet([{id: 666}, {id: 777}], function (err, cats) { + it('BatchGet items', (done) => { + Cats.Cat.batchGet([{'id': 666}, {'id': 777}], (err, cats) => { cats.length.should.eql(2); done(); }); }); - it('BatchGet items for model with falsy keys', function (done) { - Cats.Cat8.create({id: 1, age: 0}) - .then(function () { - return Cats.Cat8.batchGet([{id: 1, age: 0}]); - }) - .then(function (cats) { + it('BatchGet items for model with falsy keys', (done) => { + Cats.Cat8.create({'id': 1, 'age': 0}) + .then(() => Cats.Cat8.batchGet([{'id': 1, 'age': 0}])) + .then((cats) => { cats.length.should.eql(1); cats[0].should.have.property('id', 1); cats[0].should.have.property('age', 0); @@ -1194,10 +1186,10 @@ describe('Model', function (){ .catch(done); }); - it('Static Delete', function (done) { - Cats.Cat.delete(666, function (err) { + it('Static Delete', (done) => { + Cats.Cat.delete(666, (err) => { should.not.exist(err); - Cats.Cat.get(666, function (err, delCat) { + Cats.Cat.get(666, (err, delCat) => { should.not.exist(err); should.not.exist(delCat); @@ -1206,18 +1198,18 @@ describe('Model', function (){ }); }); - it('Should support deletions with validators', function (done) { - var cat = new Cats.CatWithGeneratedID({ - owner: { - name: 'Joe', - address: 'Somewhere' + it('Should support deletions with validators', (done) => { + const cat = new Cats.CatWithGeneratedID({ + 'owner': { + 'name': 'Joe', + 'address': 'Somewhere' }, - name: 'Garfield', - id: 'Joe_Garfield' + 'name': 'Garfield', + 'id': 'Joe_Garfield' }); - cat.delete(function (err) { + cat.delete((err) => { should.not.exist(err); - Cats.CatWithGeneratedID.get(cat, function (err, delCat) { + Cats.CatWithGeneratedID.get(cat, (err, delCat) => { should.not.exist(err); should.not.exist(delCat); done(); @@ -1225,10 +1217,10 @@ describe('Model', function (){ }); }); - it('Static Delete with range key', function (done) { - Cats.Cat2.delete({ ownerId: 666, name: 'Garfield' }, function (err) { + it('Static Delete with range key', (done) => { + Cats.Cat2.delete({'ownerId': 666, 'name': 'Garfield'}, (err) => { should.not.exist(err); - Cats.Cat2.get({ ownerId: 666, name: 'Garfield' }, function (err, delCat) { + Cats.Cat2.get({'ownerId': 666, 'name': 'Garfield'}, (err, delCat) => { should.not.exist(err); should.not.exist(delCat); done(); @@ -1236,8 +1228,8 @@ describe('Model', function (){ }); }); - it('Static Creates new item', function (done) { - Cats.Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { + it('Static Creates new item', (done) => { + Cats.Cat.create({'id': 666, 'name': 'Garfield'}, (err, garfield) => { should.not.exist(err); should.exist(garfield); garfield.id.should.eql(666); @@ -1245,13 +1237,13 @@ describe('Model', function (){ }); }); - it('Static Delete with update', function (done) { - Cats.Cat.delete(666, { update: true }, function (err, data) { + it('Static Delete with update', (done) => { + Cats.Cat.delete(666, {'update': true}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(666); data.name.should.eql('Garfield'); - Cats.Cat.get(666, function (err, delCat) { + Cats.Cat.get(666, (err, delCat) => { should.not.exist(err); should.not.exist(delCat); done(); @@ -1259,8 +1251,8 @@ describe('Model', function (){ }); }); - it('Static Delete with update failure', function (done) { - Cats.Cat.delete(666, { update: true }, function (err) { + it('Static Delete with update failure', (done) => { + Cats.Cat.delete(666, {'update': true}, (err) => { should.exist(err); err.statusCode.should.eql(400); err.code.should.eql('ConditionalCheckFailedException'); @@ -1271,47 +1263,47 @@ describe('Model', function (){ // See comments on PR #306 for details on why the test below is commented out - it('Should enable server side encryption', function() { - var Model = dynamoose.model('TestTable', { id: Number, name: String }, { serverSideEncryption: true }); + it('Should enable server side encryption', () => { + const Model = dynamoose.model('TestTable', {'id': Number, 'name': String}, {'serverSideEncryption': true}); Model.getTableReq().SSESpecification.Enabled.should.be.true; }); - it('Server side encryption shouldn\'t be enabled unless specified', function(done) { - var Model = dynamoose.model('TestTableB', { id: Number, name: String }); - setTimeout(function () { - Model.$__.table.describe(function(err, data) { - var works = !data.Table.SSEDescription || data.Table.SSEDescription.Status === 'DISABLED'; + it('Server side encryption shouldn\'t be enabled unless specified', (done) => { + const Model = dynamoose.model('TestTableB', {'id': Number, 'name': String}); + setTimeout(() => { + Model.$__.table.describe((err, data) => { + const works = !data.Table.SSEDescription || data.Table.SSEDescription.Status === 'DISABLED'; works.should.be.true; done(); }); }, 2000); }); - it('Makes model class available inside schema methods', function() { + it('Makes model class available inside schema methods', () => { Object.keys(dynamoose.models).should.containEql('test-CatWithMethods-db'); - var cat = new Cats.CatWithMethods({id: 1, name: 'Sir Pounce'}); + const cat = new Cats.CatWithMethods({'id': 1, 'name': 'Sir Pounce'}); cat.getModel.should.throw(Error); - var modelClass = cat.getModel('test-CatWithMethods-db'); + const modelClass = cat.getModel('test-CatWithMethods-db'); modelClass.should.equal(Cats.CatWithMethods); }); - describe('Model.update', function (){ - before(function (done) { - var stray = new Cats.Cat({id: 999, name: 'Tom'}); + describe('Model.update', () => { + before((done) => { + const stray = new Cats.Cat({'id': 999, 'name': 'Tom'}); stray.save(done); }); - it('False condition', function (done) { - Cats.Cat.update({id: 999}, {name: 'Oliver'}, { - condition: '#name = :name', - conditionNames: { name: 'name' }, - conditionValues: { name: 'Muffin' } - }, function (err) { + it('False condition', (done) => { + Cats.Cat.update({'id': 999}, {'name': 'Oliver'}, { + 'condition': '#name = :name', + 'conditionNames': {'name': 'name'}, + 'conditionValues': {'name': 'Muffin'} + }, (err) => { should.exist(err); - Cats.Cat.get(999, function (err, tomcat) { + Cats.Cat.get(999, (err, tomcat) => { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); @@ -1323,17 +1315,17 @@ describe('Model', function (){ }); }); - it('True condition', function (done) { - Cats.Cat.update({id: 999}, {name: 'Oliver'}, { - condition: '#name = :name', - conditionNames: { name: 'name' }, - conditionValues: { name: 'Tom' } - }, function (err, data) { + it('True condition', (done) => { + Cats.Cat.update({'id': 999}, {'name': 'Oliver'}, { + 'condition': '#name = :name', + 'conditionNames': {'name': 'name'}, + 'conditionValues': {'name': 'Tom'} + }, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Oliver'); - Cats.Cat.get(999, function (err, oliver) { + Cats.Cat.get(999, (err, oliver) => { should.not.exist(err); should.exist(oliver); oliver.id.should.eql(999); @@ -1345,29 +1337,29 @@ describe('Model', function (){ }); }); - it('If key is null or undefined, will use defaults', function (done) { - Cats.Cat3.update(null, {age: 3, name: 'Furrgie'}, function (err, data) { + it('If key is null or undefined, will use defaults', (done) => { + Cats.Cat3.update(null, {'age': 3, 'name': 'Furrgie'}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(888); data.name.should.equal('Furrgie'); data.age.should.equal(3); - Cats.Cat3.get(888, function (err, furrgie) { + Cats.Cat3.get(888, (err, furrgie) => { should.not.exist(err); should.exist(furrgie); furrgie.id.should.eql(888); furrgie.name.should.eql('Furrgie'); data.age.should.equal(3); - Cats.Cat3.update(undefined, {age: 4}, function (err, data) { + Cats.Cat3.update(undefined, {'age': 4}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(888); data.name.should.equal('Furrgie'); data.age.should.equal(4); - Cats.Cat3.get(888, function (err, furrgie) { + Cats.Cat3.get(888, (err, furrgie) => { should.not.exist(err); should.exist(furrgie); furrgie.id.should.eql(888); @@ -1381,23 +1373,23 @@ describe('Model', function (){ }); }); - it('If key is null or undefined and default isn\'t provided, will throw an error', function (done) { - Cats.Cat.update(null, {name: 'Oliver'}, function (err, data) { + it('If key is null or undefined and default isn\'t provided, will throw an error', (done) => { + Cats.Cat.update(null, {'name': 'Oliver'}, (err, data) => { should.not.exist(data); should.exist(err); done(); }); }); - it('If key is a value, will search by that value', function (done) { - Cats.Cat3.update(888, {age: 5}, function (err, data) { + it('If key is a value, will search by that value', (done) => { + Cats.Cat3.update(888, {'age': 5}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(888); data.name.should.equal('Furrgie'); data.age.should.equal(5); - Cats.Cat3.get(888, function (err, furrgie) { + Cats.Cat3.get(888, (err, furrgie) => { should.not.exist(err); should.exist(furrgie); furrgie.id.should.eql(888); @@ -1408,14 +1400,14 @@ describe('Model', function (){ }); }); - it('Creates an item with required attributes\' defaults if createRequired is true', function (done) { - Cats.Cat3.update({id: 25}, {age: 3}, {createRequired: true}, function (err, data) { + it('Creates an item with required attributes\' defaults if createRequired is true', (done) => { + Cats.Cat3.update({'id': 25}, {'age': 3}, {'createRequired': true}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(25); data.name.should.equal('Mittens'); data.age.should.equal(3); - Cats.Cat3.get(25, function (err, mittens) { + Cats.Cat3.get(25, (err, mittens) => { should.not.exist(err); should.exist(mittens); mittens.id.should.eql(25); @@ -1427,11 +1419,11 @@ describe('Model', function (){ }); }); - it('Throws an error when a required attribute has no default and has not been specified in the update if createRequired is true', function (done) { - Cats.Cat3.update({id: 25}, {name: 'Rufflestiltskins'}, {createRequired: true}, function (err, data) { + it('Throws an error when a required attribute has no default and has not been specified in the update if createRequired is true', (done) => { + Cats.Cat3.update({'id': 25}, {'name': 'Rufflestiltskins'}, {'createRequired': true}, (err, data) => { should.not.exist(data); should.exist(err); - Cats.Cat3.get(25, function (err, mittens) { + Cats.Cat3.get(25, (err, mittens) => { should.not.exist(err); should.exist(mittens); mittens.id.should.eql(25); @@ -1441,14 +1433,14 @@ describe('Model', function (){ }); }); - it('Adds required attributes, even when not specified, if createRequired is true', function (done) { - Cats.Cat3.update({id: 45}, {age: 4}, {createRequired: true}, function (err, data) { + it('Adds required attributes, even when not specified, if createRequired is true', (done) => { + Cats.Cat3.update({'id': 45}, {'age': 4}, {'createRequired': true}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(45); data.name.should.equal('Mittens'); data.age.should.equal(4); - Cats.Cat3.get(45, function (err, mittens) { + Cats.Cat3.get(45, (err, mittens) => { should.not.exist(err); should.exist(mittens); mittens.id.should.eql(45); @@ -1460,14 +1452,14 @@ describe('Model', function (){ }); }); - it('Does not add required attributes if createRequired is false', function (done) { - Cats.Cat3.update({id: 24}, {name: 'Cat-rina'}, {createRequired: false}, function (err, data) { + it('Does not add required attributes if createRequired is false', (done) => { + Cats.Cat3.update({'id': 24}, {'name': 'Cat-rina'}, {'createRequired': false}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(24); data.name.should.equal('Cat-rina'); should.not.exist(data.age); - Cats.Cat3.get(24, function (err, mittens) { + Cats.Cat3.get(24, (err, mittens) => { should.not.exist(err); should.exist(mittens); mittens.id.should.eql(24); @@ -1479,10 +1471,10 @@ describe('Model', function (){ }); }); - it('If item did not exist and timestamps are desired, createdAt and updatedAt will both be filled in', function (done) { + it('If item did not exist and timestamps are desired, createdAt and updatedAt will both be filled in', (done) => { // try a delete beforehand in case the test is run more than once - Cats.Cat4.delete({id: 22}, function () { - Cats.Cat4.update({id: 22}, {name: 'Twinkles'}, function (err, data) { + Cats.Cat4.delete({'id': 22}, () => { + Cats.Cat4.update({'id': 22}, {'name': 'Twinkles'}, (err, data) => { should.not.exist(err); should.exist(data); should.exist(data.myLittleCreatedAt); @@ -1490,7 +1482,7 @@ describe('Model', function (){ data.id.should.eql(22); data.name.should.equal('Twinkles'); - Cats.Cat4.get(22, function (err, twinkles) { + Cats.Cat4.get(22, (err, twinkles) => { should.not.exist(err); should.exist(twinkles); twinkles.id.should.eql(22); @@ -1503,10 +1495,10 @@ describe('Model', function (){ }); }); - it('UpdatedAt will be updated ', function (done) { + it('UpdatedAt will be updated ', (done) => { // try a delete beforehand in case the test is run more than once - Cats.Cat4.delete({id: 22}, function () { - Cats.Cat4.update({id: 22}, {name: 'Twinkles'}, function (err, data) { + Cats.Cat4.delete({'id': 22}, () => { + Cats.Cat4.update({'id': 22}, {'name': 'Twinkles'}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(22); @@ -1515,13 +1507,13 @@ describe('Model', function (){ should.exist(data.myLittleUpdatedAt); // now do another update - Cats.Cat4.update({id: 22}, {name: 'Furr-nando'}, function (err, data) { + Cats.Cat4.update({'id': 22}, {'name': 'Furr-nando'}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(22); data.name.should.equal('Furr-nando'); data.myLittleUpdatedAt.getTime().should.be.above(data.myLittleCreatedAt.getTime()); - Cats.Cat4.get(22, function (err, furrnando) { + Cats.Cat4.get(22, (err, furrnando) => { should.not.exist(err); should.exist(furrnando); furrnando.id.should.eql(22); @@ -1534,27 +1526,27 @@ describe('Model', function (){ }); }); - it('Expires will be updated ', function (done) { - Cats.ExpiringCat.create({name: 'Fluffy2'}) - .then(function (fluffy) { - var max = Math.floor(Date.now() / 1000) + NINE_YEARS; - var min = max - 1; + it('Expires will be updated ', (done) => { + Cats.ExpiringCat.create({'name': 'Fluffy2'}) + .then((fluffy) => { + const max = Math.floor(Date.now() / 1000) + NINE_YEARS; + const min = max - 1; should.exist(fluffy); should.exist(fluffy.expires); should.exist(fluffy.expires.getTime); - var expiresInSec = Math.floor(fluffy.expires.getTime() / 1000); + const expiresInSec = Math.floor(fluffy.expires.getTime() / 1000); expiresInSec.should.be.within(min, max); - setTimeout(function() { - Cats.ExpiringCat.update({name: 'Fluffy2'}, {name: 'Twinkles'}, { updateExpires: true }, function (err, fluffy) { + setTimeout(() => { + Cats.ExpiringCat.update({'name': 'Fluffy2'}, {'name': 'Twinkles'}, {'updateExpires': true}, (err, fluffy) => { should.not.exist(err); should.exist(fluffy); should.exist(fluffy.expires); should.exist(fluffy.expires.getTime); - var expiresInSec2 = Math.floor(fluffy.expires.getTime() / 1000); + const expiresInSec2 = Math.floor(fluffy.expires.getTime() / 1000); expiresInSec2.should.be.above(expiresInSec); done(); @@ -1564,16 +1556,16 @@ describe('Model', function (){ .catch(done); }); - it('Set expires attribute on save', function (done) { - Cats.ExpiringCat.create({name: 'Fluffy'}) - .then(function (fluffy) { - var max = Math.floor(Date.now() / 1000) + NINE_YEARS; - var min = max - 1; + it('Set expires attribute on save', (done) => { + Cats.ExpiringCat.create({'name': 'Fluffy'}) + .then((fluffy) => { + const max = Math.floor(Date.now() / 1000) + NINE_YEARS; + const min = max - 1; should.exist(fluffy); should.exist(fluffy.expires); should.exist(fluffy.expires.getTime); - var expiresInSec = Math.floor(fluffy.expires.getTime() / 1000); + const expiresInSec = Math.floor(fluffy.expires.getTime() / 1000); expiresInSec.should.be.within(min, max); done(); }) @@ -1581,19 +1573,19 @@ describe('Model', function (){ }); - it('Does not set expires attribute on save if exists', function (done) { + it('Does not set expires attribute on save if exists', (done) => { Cats.ExpiringCat.create({ - name: 'Tigger', - expires: new Date(Date.now() + (ONE_YEAR*1000)) + 'name': 'Tigger', + 'expires': new Date(Date.now() + ONE_YEAR * 1000) }) - .then(function (tigger) { - var max = Math.floor(Date.now() / 1000) + ONE_YEAR; - var min = max - 1; + .then((tigger) => { + const max = Math.floor(Date.now() / 1000) + ONE_YEAR; + const min = max - 1; should.exist(tigger); should.exist(tigger.expires); should.exist(tigger.expires.getTime); - var expiresInSec = Math.floor(tigger.expires.getTime() / 1000); + const expiresInSec = Math.floor(tigger.expires.getTime() / 1000); expiresInSec.should.be.within(min, max); done(); }) @@ -1601,23 +1593,23 @@ describe('Model', function (){ }); - it('Update expires attribute on save', function (done) { + it('Update expires attribute on save', (done) => { Cats.ExpiringCat.create({ - name: 'Leo' + 'name': 'Leo' }) - .then(function (leo) { - var max = Math.floor(Date.now() / 1000) + NINE_YEARS; - var min = max - 1; - var expiresInSec = Math.floor(leo.expires.getTime() / 1000); + .then((leo) => { + const max = Math.floor(Date.now() / 1000) + NINE_YEARS; + const min = max - 1; + const expiresInSec = Math.floor(leo.expires.getTime() / 1000); expiresInSec.should.be.within(min, max); - leo.expires = new Date(Date.now() + (ONE_YEAR* 1000)); + leo.expires = new Date(Date.now() + ONE_YEAR * 1000); return leo.save(); }) - .then(function (leo) { - var max = Math.floor(Date.now() / 1000) + ONE_YEAR; - var min = max - 1; - var expiresInSec = Math.floor(leo.expires.getTime() / 1000); + .then((leo) => { + const max = Math.floor(Date.now() / 1000) + ONE_YEAR; + const min = max - 1; + const expiresInSec = Math.floor(leo.expires.getTime() / 1000); expiresInSec.should.be.within(min, max); done(); }) @@ -1625,35 +1617,35 @@ describe('Model', function (){ }); - it('Save returnRequest option', function (done) { + it('Save returnRequest option', (done) => { Cats.ExpiringCat.create({ - name: 'Leo5' + 'name': 'Leo5' }) - .then(function (leo) { - var max = Math.floor(Date.now() / 1000) + NINE_YEARS; - var min = max - 1; - var expiresInSec = Math.floor(leo.expires.getTime() / 1000); + .then((leo) => { + const max = Math.floor(Date.now() / 1000) + NINE_YEARS; + const min = max - 1; + const expiresInSec = Math.floor(leo.expires.getTime() / 1000); expiresInSec.should.be.within(min, max); - leo.expires = new Date(Date.now() + (ONE_YEAR* 1000)); - return leo.save({returnRequest: true}); + leo.expires = new Date(Date.now() + ONE_YEAR * 1000); + return leo.save({'returnRequest': true}); }) - .then(function (request) { + .then((request) => { request.should.exist; request.TableName.should.eql('test-ExpiringCat-db'); - request.Item.name.should.eql({S: 'Leo5'}); + request.Item.name.should.eql({'S': 'Leo5'}); done(); }) .catch(done); }); - it('Should not have an expires property if TTL is set to null', function (done) { + it('Should not have an expires property if TTL is set to null', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo12' + 'name': 'Leo12' }) - .then(function () { - Cats.ExpiringCatNull.get('Leo12').then(function (leo) { + .then(() => { + Cats.ExpiringCatNull.get('Leo12').then((leo) => { should.exist(leo); should.not.exist(leo.expires); done(); @@ -1662,17 +1654,17 @@ describe('Model', function (){ .catch(done); }); - it('Should not return expired items if returnExpiredItems is false (get)', function (done) { + it('Should not return expired items if returnExpiredItems is false (get)', (done) => { Cats.ExpiringCatNoReturn.create({ - name: 'Leo1', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo1', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatNoReturn.get('Leo1').then(function (leo) { + .then(() => { + Cats.ExpiringCatNoReturn.get('Leo1').then((leo) => { should.not.exist(leo); done(); }).catch(done); @@ -1680,17 +1672,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is false and expires is null (get)', function (done) { + it('Should return expired items if returnExpiredItems is false and expires is null (get)', (done) => { Cats.ExpiringCatNoReturn.create({ - name: 'Leo11', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo11', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatNoReturn.get('Leo11').then(function (leo) { + .then(() => { + Cats.ExpiringCatNoReturn.get('Leo11').then((leo) => { should.not.exist(leo.expires); should.exist(leo); done(); @@ -1699,17 +1691,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is undefined (get)', function (done) { + it('Should return expired items if returnExpiredItems is undefined (get)', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo1', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo1', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatNull.get('Leo1').then(function (leo) { + .then(() => { + Cats.ExpiringCatNull.get('Leo1').then((leo) => { should.exist(leo); done(); }).catch(done); @@ -1717,17 +1709,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is undefined and expires is null (get)', function (done) { + it('Should return expired items if returnExpiredItems is undefined and expires is null (get)', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo11', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo11', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatNull.get('Leo11').then(function (leo) { + .then(() => { + Cats.ExpiringCatNull.get('Leo11').then((leo) => { should.not.exist(leo.expires); should.exist(leo); done(); @@ -1736,17 +1728,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is true (get)', function (done) { + it('Should return expired items if returnExpiredItems is true (get)', (done) => { Cats.ExpiringCatReturnTrue.create({ - name: 'Leo1', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo1', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatReturnTrue.get('Leo1').then(function (leo) { + .then(() => { + Cats.ExpiringCatReturnTrue.get('Leo1').then((leo) => { should.exist(leo); done(); }).catch(done); @@ -1754,17 +1746,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is true and expires is null (get)', function (done) { + it('Should return expired items if returnExpiredItems is true and expires is null (get)', (done) => { Cats.ExpiringCatReturnTrue.create({ - name: 'Leo11', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo11', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatReturnTrue.get('Leo11').then(function (leo) { + .then(() => { + Cats.ExpiringCatReturnTrue.get('Leo11').then((leo) => { should.not.exist(leo.expires); should.exist(leo); done(); @@ -1774,17 +1766,17 @@ describe('Model', function (){ }); - it('Should not return expired items if returnExpiredItems is false (batchGet)', function (done) { + it('Should not return expired items if returnExpiredItems is false (batchGet)', (done) => { Cats.ExpiringCatNoReturn.create({ - name: 'Leo2', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo2', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatNoReturn.batchGet(['Leo2']).then(function (leo) { + .then(() => { + Cats.ExpiringCatNoReturn.batchGet(['Leo2']).then((leo) => { leo.length.should.eql(0); done(); }).catch(done); @@ -1792,17 +1784,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is false and expires is null (batchGet)', function (done) { + it('Should return expired items if returnExpiredItems is false and expires is null (batchGet)', (done) => { Cats.ExpiringCatNoReturn.create({ - name: 'Leo22', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo22', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatNoReturn.batchGet(['Leo22']).then(function (leo) { + .then(() => { + Cats.ExpiringCatNoReturn.batchGet(['Leo22']).then((leo) => { leo.length.should.eql(1); should.not.exist(leo[0].expires); done(); @@ -1811,17 +1803,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is undefined (batchGet)', function (done) { + it('Should return expired items if returnExpiredItems is undefined (batchGet)', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo2', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo2', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatNull.batchGet(['Leo2']).then(function (leo) { + .then(() => { + Cats.ExpiringCatNull.batchGet(['Leo2']).then((leo) => { leo.length.should.eql(1); done(); }).catch(done); @@ -1829,17 +1821,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is undefined and expires is null (batchGet)', function (done) { + it('Should return expired items if returnExpiredItems is undefined and expires is null (batchGet)', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo22', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo22', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatNull.batchGet(['Leo22']).then(function (leo) { + .then(() => { + Cats.ExpiringCatNull.batchGet(['Leo22']).then((leo) => { leo.length.should.eql(1); should.not.exist(leo[0].expires); done(); @@ -1848,17 +1840,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is true (batchGet)', function (done) { + it('Should return expired items if returnExpiredItems is true (batchGet)', (done) => { Cats.ExpiringCatReturnTrue.create({ - name: 'Leo2', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo2', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatReturnTrue.batchGet(['Leo2']).then(function (leo) { + .then(() => { + Cats.ExpiringCatReturnTrue.batchGet(['Leo2']).then((leo) => { leo.length.should.eql(1); done(); }).catch(done); @@ -1866,17 +1858,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is true and expires is null (batchGet)', function (done) { + it('Should return expired items if returnExpiredItems is true and expires is null (batchGet)', (done) => { Cats.ExpiringCatReturnTrue.create({ - name: 'Leo22', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo22', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatReturnTrue.batchGet(['Leo22']).then(function (leo) { + .then(() => { + Cats.ExpiringCatReturnTrue.batchGet(['Leo22']).then((leo) => { leo.length.should.eql(1); should.not.exist(leo[0].expires); done(); @@ -1886,18 +1878,17 @@ describe('Model', function (){ }); - - it('Should not return expired items if returnExpiredItems is false (scan)', function (done) { + it('Should not return expired items if returnExpiredItems is false (scan)', (done) => { Cats.ExpiringCatNoReturn.create({ - name: 'Leo3', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo3', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatNoReturn.scan({name: 'Leo3'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatNoReturn.scan({'name': 'Leo3'}, (err, leo) => { if (err) { done(err); } @@ -1908,17 +1899,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is false and expires is null (scan)', function (done) { + it('Should return expired items if returnExpiredItems is false and expires is null (scan)', (done) => { Cats.ExpiringCatNoReturn.create({ - name: 'Leo33', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo33', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatNoReturn.scan({name: 'Leo33'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatNoReturn.scan({'name': 'Leo33'}, (err, leo) => { if (err) { done(err); } @@ -1930,17 +1921,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is undefined (scan)', function (done) { + it('Should return expired items if returnExpiredItems is undefined (scan)', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo3', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo3', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatNull.scan({name: 'Leo3'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatNull.scan({'name': 'Leo3'}, (err, leo) => { if (err) { done(err); } @@ -1951,17 +1942,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is undefined and expires is null (scan)', function (done) { + it('Should return expired items if returnExpiredItems is undefined and expires is null (scan)', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo33', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo33', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatNull.scan({name: 'Leo33'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatNull.scan({'name': 'Leo33'}, (err, leo) => { if (err) { done(err); } @@ -1973,17 +1964,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is true (scan)', function (done) { + it('Should return expired items if returnExpiredItems is true (scan)', (done) => { Cats.ExpiringCatReturnTrue.create({ - name: 'Leo3', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo3', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatReturnTrue.scan({name: 'Leo3'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatReturnTrue.scan({'name': 'Leo3'}, (err, leo) => { if (err) { done(err); } @@ -1994,17 +1985,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is true and expires is null (scan)', function (done) { + it('Should return expired items if returnExpiredItems is true and expires is null (scan)', (done) => { Cats.ExpiringCatReturnTrue.create({ - name: 'Leo33', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo33', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatReturnTrue.scan({name: 'Leo33'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatReturnTrue.scan({'name': 'Leo33'}, (err, leo) => { if (err) { done(err); } @@ -2016,17 +2007,17 @@ describe('Model', function (){ .catch(done); }); - it('Should not return expired items if returnExpiredItems is false (query)', function (done) { + it('Should not return expired items if returnExpiredItems is false (query)', (done) => { Cats.ExpiringCatNoReturn.create({ - name: 'Leo4', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo4', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatNoReturn.query({name: 'Leo4'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatNoReturn.query({'name': 'Leo4'}, (err, leo) => { if (err) { done(err); } @@ -2037,17 +2028,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is false and expires is null (query)', function (done) { + it('Should return expired items if returnExpiredItems is false and expires is null (query)', (done) => { Cats.ExpiringCatNoReturn.create({ - name: 'Leo44', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo44', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatNoReturn.query({name: 'Leo44'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatNoReturn.query({'name': 'Leo44'}, (err, leo) => { if (err) { done(err); } @@ -2059,17 +2050,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is undefined (query)', function (done) { + it('Should return expired items if returnExpiredItems is undefined (query)', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo4', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo4', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatNull.query({name: 'Leo4'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatNull.query({'name': 'Leo4'}, (err, leo) => { if (err) { done(err); } @@ -2080,17 +2071,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is undefined and expires is null (query)', function (done) { + it('Should return expired items if returnExpiredItems is undefined and expires is null (query)', (done) => { Cats.ExpiringCatNull.create({ - name: 'Leo44', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo44', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatNull.query({name: 'Leo44'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatNull.query({'name': 'Leo44'}, (err, leo) => { if (err) { done(err); } @@ -2102,17 +2093,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is true (query)', function (done) { + it('Should return expired items if returnExpiredItems is true (query)', (done) => { Cats.ExpiringCatReturnTrue.create({ - name: 'Leo4', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo4', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = new Date(Date.now() - 5000); return leo.save(); }) - .then(function () { - Cats.ExpiringCatReturnTrue.query({name: 'Leo4'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatReturnTrue.query({'name': 'Leo4'}, (err, leo) => { if (err) { done(err); } @@ -2123,17 +2114,17 @@ describe('Model', function (){ .catch(done); }); - it('Should return expired items if returnExpiredItems is true and expires is null (query)', function (done) { + it('Should return expired items if returnExpiredItems is true and expires is null (query)', (done) => { Cats.ExpiringCatReturnTrue.create({ - name: 'Leo44', - expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) + 'name': 'Leo44', + 'expires': new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365) }) - .then(function (leo) { + .then((leo) => { leo.expires = null; return leo.save(); }) - .then(function () { - Cats.ExpiringCatReturnTrue.query({name: 'Leo44'}, function (err, leo) { + .then(() => { + Cats.ExpiringCatReturnTrue.query({'name': 'Leo44'}, (err, leo) => { if (err) { done(err); } @@ -2155,15 +2146,13 @@ describe('Model', function (){ // }); - - - it('Updated key and update together ', function (done) { - Cats.Cat.update({id: 999, name: 'Felix'}, function (err, data) { + it('Updated key and update together ', (done) => { + Cats.Cat.update({'id': 999, 'name': 'Felix'}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Felix'); - Cats.Cat.get(999, function (err, felix){ + Cats.Cat.get(999, (err, felix) => { should.not.exist(err); should.exist(felix); felix.id.should.eql(999); @@ -2175,19 +2164,19 @@ describe('Model', function (){ }); }); - it('Updated key with range and update together ', function (done) { - Cats.Owner.create({name: 'OwnerToUpdate', address: '123 A Street', phoneNumber: '2345551212'}) - .then(function (owner) { + it('Updated key with range and update together ', (done) => { + Cats.Owner.create({'name': 'OwnerToUpdate', 'address': '123 A Street', 'phoneNumber': '2345551212'}) + .then((owner) => { owner.name.should.eql('OwnerToUpdate'); owner.phoneNumber.should.eql('2345551212'); - return Cats.Owner.update({name: 'OwnerToUpdate', address: '123 A Street', phoneNumber: 'newnumber'}); + return Cats.Owner.update({'name': 'OwnerToUpdate', 'address': '123 A Street', 'phoneNumber': 'newnumber'}); }) - .then(function (updatedOwner) { + .then((updatedOwner) => { updatedOwner.name.should.eql('OwnerToUpdate'); updatedOwner.phoneNumber.should.eql('newnumber'); - return Cats.Owner.get({name: 'OwnerToUpdate', address: '123 A Street'}); + return Cats.Owner.get({'name': 'OwnerToUpdate', 'address': '123 A Street'}); }) - .then(function (updatedOwner) { + .then((updatedOwner) => { updatedOwner.name.should.eql('OwnerToUpdate'); updatedOwner.phoneNumber.should.eql('newnumber'); done(); @@ -2195,13 +2184,13 @@ describe('Model', function (){ .catch(done); }); - it('Default puts attribute', function (done) { - Cats.Cat.update({id: 999}, {name: 'Tom'}, function (err, data) { + it('Default puts attribute', (done) => { + Cats.Cat.update({'id': 999}, {'name': 'Tom'}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Tom'); - Cats.Cat.get(999, function (err, tomcat){ + Cats.Cat.get(999, (err, tomcat) => { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); @@ -2213,13 +2202,13 @@ describe('Model', function (){ }); }); - it('Manual puts attribute with removal', function (done) { - Cats.Cat.update({id: 999}, {$PUT: {name: null}}, function (err, data) { + it('Manual puts attribute with removal', (done) => { + Cats.Cat.update({'id': 999}, {'$PUT': {'name': null}}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(999); should.not.exist(data.name); - Cats.Cat.get(999, function (err, tomcat){ + Cats.Cat.get(999, (err, tomcat) => { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); @@ -2229,13 +2218,13 @@ describe('Model', function (){ }); }); - it('Manual puts attribute', function (done) { - Cats.Cat.update({id: 999}, {$PUT: {name: 'Tom', owner: 'Jerry', age: 3}}, function (err, data) { + it('Manual puts attribute', (done) => { + Cats.Cat.update({'id': 999}, {'$PUT': {'name': 'Tom', 'owner': 'Jerry', 'age': 3}}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.owner.should.equal('Jerry'); - Cats.Cat.get(999, function (err, tomcat){ + Cats.Cat.get(999, (err, tomcat) => { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); @@ -2247,13 +2236,13 @@ describe('Model', function (){ }); }); - it('Add attribute', function (done) { - Cats.Cat.update({id: 999}, {$ADD: {age: 1}}, function (err, data) { + it('Add attribute', (done) => { + Cats.Cat.update({'id': 999}, {'$ADD': {'age': 1}}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.age.should.equal(4); - Cats.Cat.get(999, function (err, tomcat){ + Cats.Cat.get(999, (err, tomcat) => { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); @@ -2265,30 +2254,30 @@ describe('Model', function (){ }); }); - it('Add attribute to list', function (done) { - Cats.Cat13.create({id: 1000, items: [{name: 'item 2', amount: 25}]}, function () { - Cats.Cat13.update({id: 1000}, {$ADD: {items: [{name: 'item 1', amount: 50}]}}, function (err, data) { + it('Add attribute to list', (done) => { + Cats.Cat13.create({'id': 1000, 'items': [{'name': 'item 2', 'amount': 25}]}, () => { + Cats.Cat13.update({'id': 1000}, {'$ADD': {'items': [{'name': 'item 1', 'amount': 50}]}}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(1000); - data.items.should.eql([{name: 'item 2', amount: 25}, {name: 'item 1', amount: 50}]); - Cats.Cat13.get(1000, function (err, cat){ + data.items.should.eql([{'name': 'item 2', 'amount': 25}, {'name': 'item 1', 'amount': 50}]); + Cats.Cat13.get(1000, (err, cat) => { should.not.exist(err); should.exist(cat); cat.id.should.eql(1000); - cat.items.should.eql([{name: 'item 2', amount: 25}, {name: 'item 1', amount: 50}]); + cat.items.should.eql([{'name': 'item 2', 'amount': 25}, {'name': 'item 1', 'amount': 50}]); done(); }); }); }); }); - it('Delete attribute', function (done) { - Cats.Cat.update({id: 999}, {$DELETE: {owner: null}}, function (err, data) { + it('Delete attribute', (done) => { + Cats.Cat.update({'id': 999}, {'$DELETE': {'owner': null}}, (err, data) => { should.not.exist(err); should.exist(data); data.id.should.eql(999); should.not.exist(data.owner); - Cats.Cat.get(999, function (err, tomcat){ + Cats.Cat.get(999, (err, tomcat) => { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); @@ -2300,12 +2289,12 @@ describe('Model', function (){ }); }); - it('With invalid attribute', function (done) { - Cats.Cat.update({id: 999}, {name: 'Oliver', validated: 'bad'}, function (err, data) { + it('With invalid attribute', (done) => { + Cats.Cat.update({'id': 999}, {'name': 'Oliver', 'validated': 'bad'}, (err, data) => { should.exist(err); should.not.exist(data); err.name.should.equal('ValidationError'); - Cats.Cat.get(999, function (err, tomcat) { + Cats.Cat.get(999, (err, tomcat) => { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); @@ -2315,68 +2304,44 @@ describe('Model', function (){ }); }); - it('Update returns all new values using default returnValues option', function () { - return Cats.Cat.create({id: '678', name: 'Oliver'}, {overwrite: true}).then(function(old){ - return Cats.Cat.update({id: old.id}, {name: 'Tom'}).then(function(data){ - should.exist(data); - data.name.should.equal('Tom'); - data.should.have.property('id'); - }); - }); - }); + it('Update returns all new values using default returnValues option', () => Cats.Cat.create({'id': '678', 'name': 'Oliver'}, {'overwrite': true}).then((old) => Cats.Cat.update({'id': old.id}, {'name': 'Tom'}).then((data) => { + should.exist(data); + data.name.should.equal('Tom'); + data.should.have.property('id'); + }))); - it('Update respects global defaultReturnValues option', function () { - return Cats.ReturnValuesNoneCat.create({id: '678', name: 'Oliver'}, {overwrite: true}).then(function(old){ - return Cats.ReturnValuesNoneCat.update({id: old.id}, {name: 'Tom'}).then(function(data){ - should.not.exist(data); - }); - }); - }); + it('Update respects global defaultReturnValues option', () => Cats.ReturnValuesNoneCat.create({'id': '678', 'name': 'Oliver'}, {'overwrite': true}).then((old) => Cats.ReturnValuesNoneCat.update({'id': old.id}, {'name': 'Tom'}).then((data) => { + should.not.exist(data); + }))); - it('Update returns updated new values using \'UPDATED_NEW\'', function () { - return Cats.Cat.create({id: '678', name: 'Oliver'}, {overwrite: true}).then(function(old){ - return Cats.Cat.update({id: old.id}, {name: 'Tom'}, {returnValues: 'UPDATED_NEW'}).then(function(data){ - should.exist(data); - data.name.should.equal('Tom'); - data.should.not.have.property('id'); - }); - }); - }); + it('Update returns updated new values using \'UPDATED_NEW\'', () => Cats.Cat.create({'id': '678', 'name': 'Oliver'}, {'overwrite': true}).then((old) => Cats.Cat.update({'id': old.id}, {'name': 'Tom'}, {'returnValues': 'UPDATED_NEW'}).then((data) => { + should.exist(data); + data.name.should.equal('Tom'); + data.should.not.have.property('id'); + }))); - it('Update returns all new values using \'ALL_NEW\'', function () { - return Cats.Cat.create({id: '678', name: 'Oliver'}, {overwrite: true}).then(function(old){ - return Cats.Cat.update({id: old.id}, {name: 'Tom'}, {returnValues: 'ALL_NEW'}).then(function(data){ - should.exist(data); - data.name.should.equal('Tom'); - data.should.have.property('id'); - }); - }); - }); + it('Update returns all new values using \'ALL_NEW\'', () => Cats.Cat.create({'id': '678', 'name': 'Oliver'}, {'overwrite': true}).then((old) => Cats.Cat.update({'id': old.id}, {'name': 'Tom'}, {'returnValues': 'ALL_NEW'}).then((data) => { + should.exist(data); + data.name.should.equal('Tom'); + data.should.have.property('id'); + }))); - it('Update returns old updated values using \'UPDATED_OLD\'', function () { - return Cats.Cat.create({id: '679', name: 'Oliver'}, {overwrite: true}).then(function(old){ - return Cats.Cat.update({id: old.id}, {name: 'Tom'}, {returnValues: 'UPDATED_OLD'}).then(function(data){ - should.exist(data); - data.name.should.equal('Oliver'); - data.should.not.have.property('id'); - }); - }); - }); + it('Update returns old updated values using \'UPDATED_OLD\'', () => Cats.Cat.create({'id': '679', 'name': 'Oliver'}, {'overwrite': true}).then((old) => Cats.Cat.update({'id': old.id}, {'name': 'Tom'}, {'returnValues': 'UPDATED_OLD'}).then((data) => { + should.exist(data); + data.name.should.equal('Oliver'); + data.should.not.have.property('id'); + }))); - it('Update returns old values using \'ALL_OLD\'', function () { - return Cats.Cat.create({id: '679', name: 'Oliver'}, {overwrite: true}).then(function(old){ - return Cats.Cat.update({id: old.id}, {name: 'Tom'}, {returnValues: 'ALL_OLD'}).then(function(data){ - should.exist(data); - data.name.should.equal('Oliver'); - data.should.have.property('id'); - }); - }); - }); + it('Update returns old values using \'ALL_OLD\'', () => Cats.Cat.create({'id': '679', 'name': 'Oliver'}, {'overwrite': true}).then((old) => Cats.Cat.update({'id': old.id}, {'name': 'Tom'}, {'returnValues': 'ALL_OLD'}).then((data) => { + should.exist(data); + data.name.should.equal('Oliver'); + data.should.have.property('id'); + }))); - it('Update with saveUnknown enabled', function (done) { - Cats.Cat1.create({id: 982, name: 'Oliver'}, function(err, old){ + it('Update with saveUnknown enabled', (done) => { + Cats.Cat1.create({'id': 982, 'name': 'Oliver'}, (err, old) => { should.not.exist(err); - Cats.Cat1.update({id: old.id}, {otherProperty: 'Testing123'}, function(err, data){ + Cats.Cat1.update({'id': old.id}, {'otherProperty': 'Testing123'}, (err, data) => { should.not.exist(err); should.exist(data); data.should.have.property('otherProperty'); @@ -2386,12 +2351,12 @@ describe('Model', function (){ }); }); - it('Update $ADD with saveUnknown enabled', function (done) { - Cats.Cat1.create({id: 986, name: 'Oliver', mathy: 1}, function(err, old){ + it('Update $ADD with saveUnknown enabled', (done) => { + Cats.Cat1.create({'id': 986, 'name': 'Oliver', 'mathy': 1}, (err, old) => { should.not.exist(err); old.should.have.property('mathy'); old.mathy.should.eql(1); - Cats.Cat1.update({id: old.id}, {$ADD: {mathy: 4}}, function(err, data){ + Cats.Cat1.update({'id': old.id}, {'$ADD': {'mathy': 4}}, (err, data) => { should.not.exist(err); should.exist(data); data.should.have.property('mathy'); @@ -2401,15 +2366,15 @@ describe('Model', function (){ }); }); - it('Update $DELETE with saveUnknown enabled', function (done) { - Cats.Cat1.create({id: 984, name: 'Oliver'}, function(err, old){ + it('Update $DELETE with saveUnknown enabled', (done) => { + Cats.Cat1.create({'id': 984, 'name': 'Oliver'}, (err, old) => { should.not.exist(err); - Cats.Cat1.update({id: old.id}, {otherProperty: 'Testing123'}, function(err, data){ + Cats.Cat1.update({'id': old.id}, {'otherProperty': 'Testing123'}, (err, data) => { should.not.exist(err); should.exist(data); data.should.have.property('otherProperty'); data.otherProperty.should.eql('Testing123'); - Cats.Cat1.update({id: old.id}, { $DELETE: {otherProperty: 'Testing123'} }, function(err, data) { + Cats.Cat1.update({'id': old.id}, {'$DELETE': {'otherProperty': 'Testing123'}}, (err, data) => { should.not.exist(err); should.exist(data); data.should.not.have.property('otherProperty'); @@ -2419,77 +2384,69 @@ describe('Model', function (){ }); }); - it('Update returns should not return any values using \'none\' option', function () { - return Cats.Cat.create({id: '680', name: 'Oliver'}, {overwrite: true}).then(function(old){ - return Cats.Cat.update({id: old.id}, {name: 'Tom'}, {returnValues: 'NONE'}).then(function(data){ - should.not.exist(data); - }); - }); - }); + it('Update returns should not return any values using \'none\' option', () => Cats.Cat.create({'id': '680', 'name': 'Oliver'}, {'overwrite': true}).then((old) => Cats.Cat.update({'id': old.id}, {'name': 'Tom'}, {'returnValues': 'NONE'}).then((data) => { + should.not.exist(data); + }))); - it('Update returnRequest option', function (done) { - Cats.Cat.update({id: 999}, {name: 'Oliver'}, {returnRequest: true}, function(err, request) { + it('Update returnRequest option', (done) => { + Cats.Cat.update({'id': 999}, {'name': 'Oliver'}, {'returnRequest': true}, (err, request) => { should.not.exist(err); should.exist(request); request.TableName.should.eql('test-Cat-db'); - request.Key.should.eql({id: {N: '999'}}); + request.Key.should.eql({'id': {'N': '999'}}); done(); }); }); }); - describe('Model.populate', function (){ - before(function (done) { - var kittenWithParents = new Cats.Cat6({id: 1, name: 'One'}); - var owner = new Cats.Owner({name: 'Owner', address: '123 A Street', phoneNumber: '2345551212'}); - var kittenWithOwner = new Cats.CatWithOwner({ - id: 100, - name: 'Owned', - owner: {name: owner.name, address: owner.address} + describe('Model.populate', () => { + before((done) => { + const kittenWithParents = new Cats.Cat6({'id': 1, 'name': 'One'}); + const owner = new Cats.Owner({'name': 'Owner', 'address': '123 A Street', 'phoneNumber': '2345551212'}); + const kittenWithOwner = new Cats.CatWithOwner({ + 'id': 100, + 'name': 'Owned', + 'owner': {'name': owner.name, 'address': owner.address} }); kittenWithParents.save() - .then(function(kitten) { - var kittenWithParents = new Cats.Cat6({id: 2, name: 'Two', parent: kitten.id}); + .then((kitten) => { + const kittenWithParents = new Cats.Cat6({'id': 2, 'name': 'Two', 'parent': kitten.id}); return kittenWithParents.save(); }) - .then(function(kitten) { - var kittenWithParents = new Cats.Cat6({id: 3, name: 'Three', parent: kitten.id}); + .then((kitten) => { + const kittenWithParents = new Cats.Cat6({'id': 3, 'name': 'Three', 'parent': kitten.id}); return kittenWithParents.save(); }) - .then(function(kitten) { - var kittenWithParents = new Cats.Cat6({id: 4, name: 'Four', parent: kitten.id}); + .then((kitten) => { + const kittenWithParents = new Cats.Cat6({'id': 4, 'name': 'Four', 'parent': kitten.id}); return kittenWithParents.save(); }) - .then(function() { - var kittenWithParents = new Cats.Cat6({id: 5, name: 'Five', parent: 999}); + .then(() => { + const kittenWithParents = new Cats.Cat6({'id': 5, 'name': 'Five', 'parent': 999}); return kittenWithParents.save(); }) - .then(function() { - var kittenWithParents = new Cats.Cat7({id: 1, name: 'One'}); + .then(() => { + const kittenWithParents = new Cats.Cat7({'id': 1, 'name': 'One'}); return kittenWithParents.save(); }) - .then(function(kitten) { - var kittenWithParents = new Cats.Cat7({id: 2, name: 'Two', parent: kitten.id}); + .then((kitten) => { + const kittenWithParents = new Cats.Cat7({'id': 2, 'name': 'Two', 'parent': kitten.id}); return kittenWithParents.save(); }) - .then(function() { - return owner.save(); - }) - .then(function() { + .then(() => owner.save()) + .then(() => { kittenWithOwner.save(done); }); }); - it('Should populate with one parent', function (done) { + it('Should populate with one parent', (done) => { Cats.Cat6.get(4) - .then(function(cat) { - return cat.populate({ - path: 'parent', - model: 'Cat6' - }); - }) - .then(function(cat) { + .then((cat) => cat.populate({ + 'path': 'parent', + 'model': 'Cat6' + })) + .then((cat) => { should.exist(cat.parent); cat.parent.id.should.eql(3); cat.parent.name.should.eql('Three'); @@ -2497,25 +2454,23 @@ describe('Model', function (){ }); }); - it('Should deep populate with mutiple parent', function (done) { + it('Should deep populate with mutiple parent', (done) => { Cats.Cat6.get(4) - .then(function(cat) { - return cat.populate({ - path: 'parent', - model: 'Cat6', - populate: { - path: 'parent', - model: 'Cat6', - populate: { - path: 'parent', - model: 'Cat6' - } + .then((cat) => cat.populate({ + 'path': 'parent', + 'model': 'Cat6', + 'populate': { + 'path': 'parent', + 'model': 'Cat6', + 'populate': { + 'path': 'parent', + 'model': 'Cat6' } - }); - }) - .then(function(cat) { + } + })) + .then((cat) => { should.exist(cat.parent); - var parent = cat.parent; + let parent = cat.parent; parent.id.should.eql(3); parent.name.should.eql('Three'); parent = parent.parent; @@ -2529,16 +2484,16 @@ describe('Model', function (){ }); - it('Should populate with range & hash key', function (done) { + it('Should populate with range & hash key', (done) => { Cats.CatWithOwner.get(100) - .then(function(cat) { + .then((cat) => { should.not.exist(cat.owner.phoneNumber); return cat.populate({ - path: 'owner', - model: 'test-Owner' + 'path': 'owner', + 'model': 'test-Owner' }); }) - .then(function(cat) { + .then((cat) => { should.exist(cat.owner); cat.owner.name.should.eql('Owner'); cat.owner.phoneNumber.should.eql('2345551212'); @@ -2546,55 +2501,47 @@ describe('Model', function (){ }); }); - it('Populating without the model definition and without ref', function (done) { + it('Populating without the model definition and without ref', (done) => { Cats.Cat7.get(2) - .then(function(cat) { - return cat.populate({ - path: 'parent' - }); - }) - .catch(function(err){ + .then((cat) => cat.populate({ + 'path': 'parent' + })) + .catch((err) => { should.exist(err.message); done(); }); }); - it('Populating with model and without the path definition', function (done) { + it('Populating with model and without the path definition', (done) => { Cats.Cat6.get(4) - .then(function(cat) { - return cat.populate({ - model: 'Cat6' - }); - }) - .catch(function(err){ + .then((cat) => cat.populate({ + 'model': 'Cat6' + })) + .catch((err) => { should.exist(err.message); done(); }); }); - it('Populating with the wrong reference id', function (done) { + it('Populating with the wrong reference id', (done) => { Cats.Cat6.get(5) - .then(function(cat) { - return cat.populate({ - path: 'parent', - model: 'Cat6' - }); - }) - .catch(function(err){ + .then((cat) => cat.populate({ + 'path': 'parent', + 'model': 'Cat6' + })) + .catch((err) => { should.exist(err.message); done(); }); }); - it('Populate works with hashkey', function (done) { + it('Populate works with hashkey', (done) => { Cats.Cat7.get(2) - .then(function(cat) { - return cat.populate({ - path: 'parent', - model: 'Cat7' - }); - }) - .then(function(cat) { + .then((cat) => cat.populate({ + 'path': 'parent', + 'model': 'Cat7' + })) + .then((cat) => { should.exist(cat.parent); cat.parent.id.should.eql(1); cat.parent.name.should.eql('One'); @@ -2602,15 +2549,13 @@ describe('Model', function (){ }); }); - it('Populate works with prefix', function (done) { + it('Populate works with prefix', (done) => { Cats.Cat6.get(4) - .then(function(cat) { - return cat.populate({ - path: 'parent', - model: 'test-Cat6-db' - }); - }) - .then(function(cat) { + .then((cat) => cat.populate({ + 'path': 'parent', + 'model': 'test-Cat6-db' + })) + .then((cat) => { should.exist(cat.parent); cat.parent.id.should.eql(3); cat.parent.name.should.eql('Three'); @@ -2618,44 +2563,38 @@ describe('Model', function (){ }); }); - it('Populating with the wrong model name won\'t work', function (done) { + it('Populating with the wrong model name won\'t work', (done) => { Cats.Cat6.get(5) - .then(function(cat) { - return cat.populate({ - path: 'parent', - model: 'Cats6' - }); - }) - .catch(function(err){ + .then((cat) => cat.populate({ + 'path': 'parent', + 'model': 'Cats6' + })) + .catch((err) => { should.exist(err.message); done(); }); }); - it('Populating with path and ref at the schema', function (done) { + it('Populating with path and ref at the schema', (done) => { Cats.Cat6.get(4) - .then(function(cat) { - return cat.populate({ - path: 'parent' - }); - }) - .then(function(cat) { + .then((cat) => cat.populate({ + 'path': 'parent' + })) + .then((cat) => { should.exist(cat.parent); - var parent = cat.parent; + const parent = cat.parent; parent.id.should.eql(3); parent.name.should.eql('Three'); done(); }); }); - it('Populating with string and ref at the schema', function (done) { + it('Populating with string and ref at the schema', (done) => { Cats.Cat6.get(4) - .then(function(cat) { - return cat.populate('parent'); - }) - .then(function(cat) { + .then((cat) => cat.populate('parent')) + .then((cat) => { should.exist(cat.parent); - var parent = cat.parent; + const parent = cat.parent; parent.id.should.eql(3); parent.name.should.eql('Three'); done(); @@ -2664,26 +2603,26 @@ describe('Model', function (){ }); - describe('Model.batchPut', function (){ + describe('Model.batchPut', () => { - it('Put new', function (done) { - var cats = []; + it('Put new', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat({id: 10+i, name: 'Tom_'+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat({'id': 10 + i, 'name': `Tom_${i}`})); } - Cats.Cat.batchPut(cats, function (err, result) { + Cats.Cat.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); - for (var i=0 ; i<10 ; i += 1) { + for (let i = 0; i < 10; i += 1) { delete cats[i].name; } - Cats.Cat.batchGet(cats, function (err2, result2) { + Cats.Cat.batchGet(cats, (err2, result2) => { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); @@ -2692,23 +2631,23 @@ describe('Model', function (){ }); }); - it('Put lots of new items', function (done) { - var cats = []; + it('Put lots of new items', (done) => { + const cats = []; - for (var i=0 ; i<100 ; i += 1) { - cats.push(new Cats.Cat({id: 100+i, name: 'Tom_'+i})); + for (let i = 0; i < 100; i += 1) { + cats.push(new Cats.Cat({'id': 100 + i, 'name': `Tom_${i}`})); } - Cats.Cat.batchPut(cats, function (err, result) { + Cats.Cat.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); - for (var i=0 ; i<100 ; i += 1) { + for (let i = 0; i < 100; i += 1) { delete cats[i].name; } - Cats.Cat.batchGet(cats, function (err2, result2) { + Cats.Cat.batchGet(cats, (err2, result2) => { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); @@ -2717,19 +2656,19 @@ describe('Model', function (){ }); }); - it('Put new with range key', function (done) { - var cats = []; + it('Put new with range key', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat2({ownerId: 10+i, name: 'Tom_'+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat2({'ownerId': 10 + i, 'name': `Tom_${i}`})); } - Cats.Cat2.batchPut(cats, function (err, result) { + Cats.Cat2.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); - Cats.Cat2.batchGet(cats, function (err2, result2) { + Cats.Cat2.batchGet(cats, (err2, result2) => { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); @@ -2738,46 +2677,46 @@ describe('Model', function (){ }); }); - it('Put new without range key', function (done) { - var cats = []; + it('Put new without range key', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat2({ownerId: 10+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat2({'ownerId': 10 + i})); } - Cats.Cat2.batchPut(cats, function (err, result) { + Cats.Cat2.batchPut(cats, (err, result) => { should.exist(err); should.not.exist(result); done(); }); }); - it('Update items', function (done) { - var cats = []; + it('Update items', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat({id: 20+i, name: 'Tom_'+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat({'id': 20 + i, 'name': `Tom_${i}`})); } - Cats.Cat.batchPut(cats, function (err, result) { + Cats.Cat.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); - for (var i=0 ; i<10 ; i += 1) { - var cat = cats[i]; - cat.name = 'John_' + (cat.id + 100); + for (let i = 0; i < 10; i += 1) { + const cat = cats[i]; + cat.name = `John_${cat.id + 100}`; } - Cats.Cat.batchPut(cats, function (err2, result2) { + Cats.Cat.batchPut(cats, (err2, result2) => { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); - for (var i=0 ; i<10 ; i += 1) { + for (let i = 0; i < 10; i += 1) { delete cats[i].name; } - Cats.Cat.batchGet(cats, function (err3, result3) { + Cats.Cat.batchGet(cats, (err3, result3) => { should.not.exist(err3); should.exist(result3); result3.length.should.eql(cats.length); @@ -2787,28 +2726,28 @@ describe('Model', function (){ }); }); - it('Update with range key', function (done) { - var cats = []; + it('Update with range key', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat2({ownerId: 20+i, name: 'Tom_'+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat2({'ownerId': 20 + i, 'name': `Tom_${i}`})); } - Cats.Cat2.batchPut(cats, function (err, result) { + Cats.Cat2.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); - for (var i=0 ; i<10 ; i += 1) { - var cat = cats[i]; - cat.name = 'John_' + (cat.ownerId + 100); + for (let i = 0; i < 10; i += 1) { + const cat = cats[i]; + cat.name = `John_${cat.ownerId + 100}`; } - Cats.Cat2.batchPut(cats, function (err2, result2) { + Cats.Cat2.batchPut(cats, (err2, result2) => { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); - Cats.Cat2.batchGet(cats, function (err3, result3) { + Cats.Cat2.batchGet(cats, (err3, result3) => { should.not.exist(err3); should.exist(result3); result3.length.should.eql(cats.length); @@ -2818,22 +2757,22 @@ describe('Model', function (){ }); }); - it('Update without range key', function (done) { - var cats = []; + it('Update without range key', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat2({ownerId: 20+i, name: 'Tom_'+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat2({'ownerId': 20 + i, 'name': `Tom_${i}`})); } - Cats.Cat2.batchPut(cats, function (err, result) { + Cats.Cat2.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); - for (var i=0 ; i<10 ; i += 1) { + for (let i = 0; i < 10; i += 1) { cats[i].name = null; } - Cats.Cat2.batchPut(cats, function (err2, result2) { + Cats.Cat2.batchPut(cats, (err2, result2) => { should.exist(err2); should.not.exist(result2); done(); @@ -2841,21 +2780,21 @@ describe('Model', function (){ }); }); - it('Update without updateTimestamps (default)', async function () { + it('Update without updateTimestamps (default)', async () => { const cats = [...Array(10)] - .map((_, i) => new Cats.Cat4({ id: i + 1, name: 'Tom_' + i })); + .map((_, i) => new Cats.Cat4({'id': i + 1, 'name': `Tom_${i}`})); const result = await Cats.Cat4.batchPut(cats); should.exist(result); const timestamps = {}; cats.forEach((cat, i) => { - const { id, myLittleUpdatedAt } = cat; - cat.name = 'John_' + i; + const {id, myLittleUpdatedAt} = cat; + cat.name = `John_${i}`; timestamps[id] = new Date(myLittleUpdatedAt); }); - await new Promise(resolve => setTimeout(resolve, 1000)); + await new Promise((resolve) => setTimeout(resolve, 1000)); const result2 = await Cats.Cat4.batchPut(cats); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); @@ -2863,86 +2802,86 @@ describe('Model', function (){ const updatedCats = await Cats.Cat4.batchGet(cats); should.exist(updatedCats); updatedCats.length.should.eql(cats.length); - updatedCats.forEach(cat => { + updatedCats.forEach((cat) => { cat.myLittleUpdatedAt.should.eql(timestamps[cat.id]); }); }); - it('Update with updateTimestamps set to false', async function () { + it('Update with updateTimestamps set to false', async () => { const cats = [...Array(10)] - .map((_, i) => new Cats.Cat4({ id: i + 1, name: 'Tom_' + i })); + .map((_, i) => new Cats.Cat4({'id': i + 1, 'name': `Tom_${i}`})); const result = await Cats.Cat4.batchPut(cats); should.exist(result); const timestamps = {}; cats.forEach((cat, i) => { - const { id, myLittleUpdatedAt } = cat; - cat.name = 'John_' + i; + const {id, myLittleUpdatedAt} = cat; + cat.name = `John_${i}`; timestamps[id] = new Date(myLittleUpdatedAt); }); - await new Promise(resolve => setTimeout(resolve, 1000)); - const result2 = await Cats.Cat4.batchPut(cats, { updateTimestamps: false }); + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result2 = await Cats.Cat4.batchPut(cats, {'updateTimestamps': false}); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); const updatedCats = await Cats.Cat4.batchGet(cats); should.exist(updatedCats); updatedCats.length.should.eql(cats.length); - updatedCats.forEach(cat => { + updatedCats.forEach((cat) => { cat.myLittleUpdatedAt.should.eql(timestamps[cat.id]); }); }); - it('Update with updateTimestamps set to true', async function () { + it('Update with updateTimestamps set to true', async () => { const cats = [...Array(10)] - .map((_, i) => new Cats.Cat4({ id: i + 1, name: 'Tom_' + i })); + .map((_, i) => new Cats.Cat4({'id': i + 1, 'name': `Tom_${i}`})); const result = await Cats.Cat4.batchPut(cats); should.exist(result); const timestamps = {}; cats.forEach((cat, i) => { - const { id, myLittleUpdatedAt } = cat; - cat.name = 'John_' + i; + const {id, myLittleUpdatedAt} = cat; + cat.name = `John_${i}`; timestamps[id] = new Date(myLittleUpdatedAt); }); - await new Promise(resolve => setTimeout(resolve, 1000)); - const result2 = await Cats.Cat4.batchPut(cats, { updateTimestamps: true }); + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result2 = await Cats.Cat4.batchPut(cats, {'updateTimestamps': true}); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); const updatedCats = await Cats.Cat4.batchGet(cats); should.exist(updatedCats); updatedCats.length.should.eql(cats.length); - updatedCats.forEach(cat => { + updatedCats.forEach((cat) => { cat.myLittleUpdatedAt.should.be.greaterThan(timestamps[cat.id]); }); }); - it('Update without updateExpires (default)', async function () { + it('Update without updateExpires (default)', async () => { const cats = [ new Cats.Cat11({ - id: 1, - name: 'Crookshanks', - vet: { name: 'theVet', address: 'Diagon Alley' }, - ears: [{ name: 'left' }, { name: 'right' }], - legs: ['front right', 'front left', 'back right', 'back left'], - more: { favorites: { food: 'fish' } }, - array: [{ one: '1' }], - validated: 'valid' + 'id': 1, + 'name': 'Crookshanks', + 'vet': {'name': 'theVet', 'address': 'Diagon Alley'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }), new Cats.Cat11({ - id: 2, - name: 'Behemoth', - vet: { name:'Mikhail Bulgakov', address:'Moscow' }, - ears: [{ name: 'left' }, { name: 'right' }], - legs: ['front right', 'front left', 'back right', 'back left'], - more: { favorites: { drink: 'pure alcohol' } }, - array: [{ one: '1' }], - validated: 'valid' + 'id': 2, + 'name': 'Behemoth', + 'vet': {'name': 'Mikhail Bulgakov', 'address': 'Moscow'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'drink': 'pure alcohol'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }) ]; @@ -2954,12 +2893,12 @@ describe('Model', function (){ savedCats.length.should.eql(cats.length); const originalExpires = {}; - savedCats.forEach(cat => { - cat.array.push({ two: '2' }); + savedCats.forEach((cat) => { + cat.array.push({'two': '2'}); originalExpires[cat.id] = cat.expires; }); - await new Promise(resolve => setTimeout(resolve, 1000)); + await new Promise((resolve) => setTimeout(resolve, 1000)); const result2 = await Cats.Cat11.batchPut(savedCats); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); @@ -2973,27 +2912,27 @@ describe('Model', function (){ }); }); - it('Update with updateExpires set to false', async function () { + it('Update with updateExpires set to false', async () => { const cats = [ new Cats.Cat11({ - id: 1, - name: 'Crookshanks', - vet: { name: 'theVet', address: 'Diagon Alley' }, - ears: [{ name: 'left' }, { name: 'right' }], - legs: ['front right', 'front left', 'back right', 'back left'], - more: { favorites: { food: 'fish' } }, - array: [{ one: '1' }], - validated: 'valid' + 'id': 1, + 'name': 'Crookshanks', + 'vet': {'name': 'theVet', 'address': 'Diagon Alley'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }), new Cats.Cat11({ - id: 2, - name: 'Behemoth', - vet: { name:'Mikhail Bulgakov', address:'Moscow' }, - ears: [{ name: 'left' }, { name: 'right' }], - legs: ['front right', 'front left', 'back right', 'back left'], - more: { favorites: { drink: 'pure alcohol' } }, - array: [{ one: '1' }], - validated: 'valid' + 'id': 2, + 'name': 'Behemoth', + 'vet': {'name': 'Mikhail Bulgakov', 'address': 'Moscow'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'drink': 'pure alcohol'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }) ]; @@ -3005,13 +2944,13 @@ describe('Model', function (){ savedCats.length.should.eql(cats.length); const originalExpires = {}; - savedCats.forEach(cat => { - cat.array.push({ two: '2' }); + savedCats.forEach((cat) => { + cat.array.push({'two': '2'}); originalExpires[cat.id] = cat.expires; }); - await new Promise(resolve => setTimeout(resolve, 1000)); - const result2 = await Cats.Cat11.batchPut(savedCats, { updateExpires: false }); + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result2 = await Cats.Cat11.batchPut(savedCats, {'updateExpires': false}); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); @@ -3024,27 +2963,27 @@ describe('Model', function (){ }); }); - it('Update with updateExpires set to true', async function () { + it('Update with updateExpires set to true', async () => { const cats = [ new Cats.Cat11({ - id: 1, - name: 'Crookshanks', - vet: { name: 'theVet', address: 'Diagon Alley' }, - ears: [{ name: 'left' }, { name: 'right' }], - legs: ['front right', 'front left', 'back right', 'back left'], - more: { favorites: { food: 'fish' } }, - array: [{ one: '1' }], - validated: 'valid' + 'id': 1, + 'name': 'Crookshanks', + 'vet': {'name': 'theVet', 'address': 'Diagon Alley'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }), new Cats.Cat11({ - id: 2, - name: 'Behemoth', - vet: { name:'Mikhail Bulgakov', address:'Moscow' }, - ears: [{ name: 'left' }, { name: 'right' }], - legs: ['front right', 'front left', 'back right', 'back left'], - more: { favorites: { drink: 'pure alcohol' } }, - array: [{ one: '1' }], - validated: 'valid' + 'id': 2, + 'name': 'Behemoth', + 'vet': {'name': 'Mikhail Bulgakov', 'address': 'Moscow'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'drink': 'pure alcohol'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' }) ]; @@ -3056,13 +2995,13 @@ describe('Model', function (){ savedCats.length.should.eql(cats.length); const originalExpires = {}; - savedCats.forEach(cat => { - cat.array.push({ two: '2' }); + savedCats.forEach((cat) => { + cat.array.push({'two': '2'}); originalExpires[cat.id] = cat.expires; }); - await new Promise(resolve => setTimeout(resolve, 1000)); - const result2 = await Cats.Cat11.batchPut(savedCats, { updateExpires: true }); + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result2 = await Cats.Cat11.batchPut(savedCats, {'updateExpires': true}); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); @@ -3075,18 +3014,18 @@ describe('Model', function (){ }); }); - it('Works with multiple Array globals', async function () { + it('Works with multiple Array globals', async () => { const catsUsingOriginalArrayGlobal = [ new Cats.Cat11({ - id: 1, - name: 'Crookshanks', - vet: { name: 'theVet', address: 'Diagon Alley' }, - ears: [{ name: 'left' }, { name: 'right' }], - legs: ['front right', 'front left', 'back right', 'back left'], - more: { favorites: { food: 'fish' } }, - array: [{ one: '1' }], - validated: 'valid' - }), + 'id': 1, + 'name': 'Crookshanks', + 'vet': {'name': 'theVet', 'address': 'Diagon Alley'}, + 'ears': [{'name': 'left'}, {'name': 'right'}], + 'legs': ['front right', 'front left', 'back right', 'back left'], + 'more': {'favorites': {'food': 'fish'}}, + 'array': [{'one': '1'}], + 'validated': 'valid' + }) ]; const arrayPrototypeClone = {}; for (const method of Object.getOwnPropertyNames(Array.prototype)) { @@ -3098,24 +3037,24 @@ describe('Model', function (){ }); }); - describe('Model.batchDelete', function (){ - it('Simple delete', function (done) { - var cats = []; + describe('Model.batchDelete', () => { + it('Simple delete', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat({id: 30+i, name: 'Tom_'+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat({'id': 30 + i, 'name': `Tom_${i}`})); } - Cats.Cat.batchPut(cats, function (err, result) { + Cats.Cat.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); - Cats.Cat.batchDelete(cats, function (err2, result2) { + Cats.Cat.batchDelete(cats, (err2, result2) => { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); - Cats.Cat.batchGet(cats, function (err3, result3) { + Cats.Cat.batchGet(cats, (err3, result3) => { should.not.exist(err3); should.exist(result3); result3.length.should.eql(0); @@ -3125,23 +3064,23 @@ describe('Model', function (){ }); }); - it('Delete with range key', function (done) { - var cats = []; + it('Delete with range key', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat2({ownerId: 30+i, name: 'Tom_'+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat2({'ownerId': 30 + i, 'name': `Tom_${i}`})); } - Cats.Cat2.batchPut(cats, function (err, result) { + Cats.Cat2.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); - Cats.Cat2.batchDelete(cats, function (err2, result2) { + Cats.Cat2.batchDelete(cats, (err2, result2) => { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); - Cats.Cat2.batchGet(cats, function (err3, result3) { + Cats.Cat2.batchGet(cats, (err3, result3) => { should.not.exist(err3); should.exist(result3); result3.length.should.eql(0); @@ -3151,22 +3090,22 @@ describe('Model', function (){ }); }); - it('Delete without range key', function (done) { - var cats = []; + it('Delete without range key', (done) => { + const cats = []; - for (var i=0 ; i<10 ; i += 1) { - cats.push(new Cats.Cat2({ownerId: 30+i, name: 'Tom_'+i})); + for (let i = 0; i < 10; i += 1) { + cats.push(new Cats.Cat2({'ownerId': 30 + i, 'name': `Tom_${i}`})); } - Cats.Cat2.batchPut(cats, function (err, result) { + Cats.Cat2.batchPut(cats, (err, result) => { should.not.exist(err); should.exist(result); - for (var i=0 ; i<10 ; i += 1) { + for (let i = 0; i < 10; i += 1) { delete cats[i].name; } - Cats.Cat2.batchDelete(cats, function (err2, result2) { + Cats.Cat2.batchDelete(cats, (err2, result2) => { should.exist(err2); should.not.exist(result2); done(); @@ -3177,20 +3116,20 @@ describe('Model', function (){ }); - describe('Model.default', function() { - it('Default is set properly', function() { - var cat = new Cats.CatModel({ - id: 1111, - name: 'NAME_VALUE', - owner: 'OWNER_VALUE', - shouldRemainUnchanged: 'AAA', - shouldBeChanged: undefined, - shouldAlwaysBeChanged: 'BBB' + describe('Model.default', () => { + it('Default is set properly', () => { + const cat = new Cats.CatModel({ + 'id': 1111, + 'name': 'NAME_VALUE', + 'owner': 'OWNER_VALUE', + 'shouldRemainUnchanged': 'AAA', + 'shouldBeChanged': undefined, + 'shouldAlwaysBeChanged': 'BBB' }); return cat .save() - .then(function() { + .then(() => { should(cat.shouldRemainUnchanged).eql('AAA'); should(cat.shouldBeChanged).eql('shouldBeChanged_NAME_VALUE_OWNER_VALUE'); should(cat.shouldAlwaysBeChanged).eql('shouldAlwaysBeChanged_NAME_VALUE_OWNER_VALUE'); @@ -3200,7 +3139,7 @@ describe('Model', function (){ }); }); - it('Model.getTableReq', function() { + it('Model.getTableReq', () => { Cats.Cat.getTableReq().AttributeDefinitions.should.exist; Cats.Cat.getTableReq().TableName.should.exist; Cats.Cat.getTableReq().TableName.should.equal('test-Cat-db'); @@ -3208,91 +3147,91 @@ describe('Model', function (){ Cats.Cat.getTableReq().ProvisionedThroughput.should.exist; }); - it('Should have BillingMode set to PROVISIONED when creating table, and no throughput defined', function() { - var BillModeSchema1 = new dynamoose.Schema({ - id: Number, - name: String + it('Should have BillingMode set to PROVISIONED when creating table, and no throughput defined', () => { + const BillModeSchema1 = new dynamoose.Schema({ + 'id': Number, + 'name': String }); - var BillModeModel1 = dynamoose.model('BillModeModel1', BillModeSchema1); + const BillModeModel1 = dynamoose.model('BillModeModel1', BillModeSchema1); BillModeModel1.getTableReq().BillingMode.should.eql('PROVISIONED'); }); - it('Should have BillingMode set to PROVISIONED when creating table, and throughput defined', function() { - var BillModeSchema2 = new dynamoose.Schema({ - id: Number, - name: String - }, {throughput: { - write: 10, - read: 10 + it('Should have BillingMode set to PROVISIONED when creating table, and throughput defined', () => { + const BillModeSchema2 = new dynamoose.Schema({ + 'id': Number, + 'name': String + }, {'throughput': { + 'write': 10, + 'read': 10 }}); - var BillModeModel2 = dynamoose.model('BillModeModel2', BillModeSchema2); + const BillModeModel2 = dynamoose.model('BillModeModel2', BillModeSchema2); BillModeModel2.getTableReq().BillingMode.should.eql('PROVISIONED'); }); - it('Should have BillingMode set to PAY_PER_REQUEST when creating table, and throughput is ON_DEMAND', function() { - var BillModeSchema3 = new dynamoose.Schema({ - id: Number, - name: String - }, {throughput: 'ON_DEMAND'}); - var BillModeModel3 = dynamoose.model('BillModeModel3', BillModeSchema3, {create: false}); + it('Should have BillingMode set to PAY_PER_REQUEST when creating table, and throughput is ON_DEMAND', () => { + const BillModeSchema3 = new dynamoose.Schema({ + 'id': Number, + 'name': String + }, {'throughput': 'ON_DEMAND'}); + const BillModeModel3 = dynamoose.model('BillModeModel3', BillModeSchema3, {'create': false}); BillModeModel3.getTableReq().BillingMode.should.eql('PAY_PER_REQUEST'); }); - it('Should have correct throughput set when set', function() { - var BillModeSchema4 = new dynamoose.Schema({ - id: Number, - name: String - }, {throughput: { - write: 10, - read: 10 + it('Should have correct throughput set when set', () => { + const BillModeSchema4 = new dynamoose.Schema({ + 'id': Number, + 'name': String + }, {'throughput': { + 'write': 10, + 'read': 10 }}); - var BillModeModel4 = dynamoose.model('BillModeModel4', BillModeSchema4, {create: false}); + const BillModeModel4 = dynamoose.model('BillModeModel4', BillModeSchema4, {'create': false}); BillModeModel4.getTableReq().ProvisionedThroughput.ReadCapacityUnits.should.eql(10); BillModeModel4.getTableReq().ProvisionedThroughput.WriteCapacityUnits.should.eql(10); }); - it('Should not have throughput on Global Secondary Index if Model throughput is ON_DEMAND', function() { - var BillModeSchema5 = new dynamoose.Schema({ - id: Number, - name: { type: String, index: { global: true } } - }, {throughput: 'ON_DEMAND'}); - var BillModeModel5 = dynamoose.model('BillModeModel5', BillModeSchema5, {create: false}); + it('Should not have throughput on Global Secondary Index if Model throughput is ON_DEMAND', () => { + const BillModeSchema5 = new dynamoose.Schema({ + 'id': Number, + 'name': {'type': String, 'index': {'global': true}} + }, {'throughput': 'ON_DEMAND'}); + const BillModeModel5 = dynamoose.model('BillModeModel5', BillModeSchema5, {'create': false}); should.not.exist(BillModeModel5.getTableReq().GlobalSecondaryIndexes[0].ProvisionedThroughput); }); - it('Should have correct throughput on Global Secondary Index if Model throughput is set', function() { - var BillModeSchema6 = new dynamoose.Schema({ - id: Number, - name: { type: String, index: { global: true, throughput: { write: 5, read: 5 } } } - }, {throughput: { - write: 10, - read: 10 + it('Should have correct throughput on Global Secondary Index if Model throughput is set', () => { + const BillModeSchema6 = new dynamoose.Schema({ + 'id': Number, + 'name': {'type': String, 'index': {'global': true, 'throughput': {'write': 5, 'read': 5}}} + }, {'throughput': { + 'write': 10, + 'read': 10 }}); - var BillModeModel6 = dynamoose.model('BillModeModel6', BillModeSchema6, {create: false}); + const BillModeModel6 = dynamoose.model('BillModeModel6', BillModeSchema6, {'create': false}); BillModeModel6.getTableReq().GlobalSecondaryIndexes[0].ProvisionedThroughput.ReadCapacityUnits.should.eql(5); BillModeModel6.getTableReq().GlobalSecondaryIndexes[0].ProvisionedThroughput.WriteCapacityUnits.should.eql(5); }); - it('Should allow for originalItem function on models', function(done) { - var item = { - id: 2222, - name: 'NAME_VALUE', - owner: 'OWNER_VALUE' + it('Should allow for originalItem function on models', (done) => { + const item = { + 'id': 2222, + 'name': 'NAME_VALUE', + 'owner': 'OWNER_VALUE' }; - var cat = new Cats.Cat(item); + const cat = new Cats.Cat(item); cat.originalItem().should.eql(item); - cat.save(function(err, newCat) { + cat.save((err, newCat) => { newCat.originalItem().should.eql(item); newCat.name = 'NAME_VALUE_2'; newCat.originalItem().should.eql(item); newCat.name.should.eql('NAME_VALUE_2'); - Cats.Cat.get(2222, function(err, newCatB) { + Cats.Cat.get(2222, (err, newCatB) => { newCatB.originalItem().should.eql(item); newCatB.name = 'NAME_VALUE_2'; newCatB.originalItem().should.eql(item); @@ -3302,23 +3241,23 @@ describe('Model', function (){ }); }); - it('Should store/load binary data safely', function(done) { - var imageData = Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xd3, 0x61, 0x60, 0x60]); + it('Should store/load binary data safely', (done) => { + const imageData = Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xd3, 0x61, 0x60, 0x60]); imageData.should.not.eql(Buffer.from(imageData.toString())); // The binary value should not be UTF-8 string for test. - var item = { - id: 3333, - name: 'NAME_VALUE', - owner: 'OWNER_VALUE', - profileImage: imageData + const item = { + 'id': 3333, + 'name': 'NAME_VALUE', + 'owner': 'OWNER_VALUE', + 'profileImage': imageData }; - var cat = new Cats.Cat(item); - cat.save(function(err) { + const cat = new Cats.Cat(item); + cat.save((err) => { should.not.exist(err); - Cats.Cat.get(3333, function(err, newCatB) { + Cats.Cat.get(3333, (err, newCatB) => { should.not.exist(err); should.exist(newCatB); newCatB.should.have.property('profileImage', imageData); @@ -3327,23 +3266,23 @@ describe('Model', function (){ }); }); - describe('Model.transaction', function() { - it('Model.transaction should exist and be an object', function() { + describe('Model.transaction', () => { + it('Model.transaction should exist and be an object', () => { should.exist(Cats.Cat.transaction); Cats.Cat.transaction.should.be.instanceof(Object); }); describe('Model.transaction.get', () => { - it('Model.transaction.get should work', function(done) { - Cats.Cat.transaction.get('1').then(function(result) { + it('Model.transaction.get should work', (done) => { + Cats.Cat.transaction.get('1').then((result) => { should.exist(result); should.exist(result.Get); done(); }).catch(done); }); - it('Model.transaction.get should work with options', function(done) { - Cats.Cat.transaction.get('1', {consistent: true}).then(function(result) { + it('Model.transaction.get should work with options', (done) => { + Cats.Cat.transaction.get('1', {'consistent': true}).then((result) => { should.exist(result); should.exist(result.Get); @@ -3353,16 +3292,16 @@ describe('Model', function (){ }); }); describe('Model.transaction.delete', () => { - it('Model.transaction.delete should work', function(done) { - Cats.Cat.transaction.delete('1').then(function(result) { + it('Model.transaction.delete should work', (done) => { + Cats.Cat.transaction.delete('1').then((result) => { should.exist(result); should.exist(result.Delete); done(); }).catch(done); }); - it('Model.transaction.delete should work with options', function(done) { - Cats.Cat.transaction.delete('1', {update: true}).then(function(result) { + it('Model.transaction.delete should work with options', (done) => { + Cats.Cat.transaction.delete('1', {'update': true}).then((result) => { should.exist(result); should.exist(result.Delete); @@ -3372,16 +3311,16 @@ describe('Model', function (){ }); }); describe('Model.transaction.create', () => { - it('Model.transaction.create should work', function(done) { - Cats.Cat.transaction.create({id: 1}).then(function(result) { + it('Model.transaction.create should work', (done) => { + Cats.Cat.transaction.create({'id': 1}).then((result) => { should.exist(result); should.exist(result.Put); done(); }).catch(done); }); - it('Model.transaction.create should work with options', function(done) { - Cats.Cat.transaction.create({id: 1}, {overwrite: true}).then(function(result) { + it('Model.transaction.create should work with options', (done) => { + Cats.Cat.transaction.create({'id': 1}, {'overwrite': true}).then((result) => { should.exist(result); should.exist(result.Put); @@ -3391,8 +3330,8 @@ describe('Model', function (){ }); }); describe('Model.transaction.update', () => { - it('Model.transaction.update should work if combined', function(done) { - Cats.Cat.transaction.update({id: 1, name: 'Bob'}).then(function(result) { + it('Model.transaction.update should work if combined', (done) => { + Cats.Cat.transaction.update({'id': 1, 'name': 'Bob'}).then((result) => { should.exist(result); should.exist(result.Update); should.exist(result.Update.TableName); @@ -3400,8 +3339,8 @@ describe('Model', function (){ done(); }).catch(done); }); - it('Model.transaction.update should work if seperate', function(done) { - Cats.Cat.transaction.update({id: 1}, {name: 'Bob'}).then(function(result) { + it('Model.transaction.update should work if seperate', (done) => { + Cats.Cat.transaction.update({'id': 1}, {'name': 'Bob'}).then((result) => { should.exist(result); should.exist(result.Update); should.exist(result.Update.TableName); @@ -3409,8 +3348,8 @@ describe('Model', function (){ done(); }).catch(done); }); - it('Model.transaction.update should work with options seperate', function(done) { - Cats.Cat.transaction.update({id: 1}, {name: 'Bob'}, {condition: 'attribute_not_exists(name)'}).then(function(result) { + it('Model.transaction.update should work with options seperate', (done) => { + Cats.Cat.transaction.update({'id': 1}, {'name': 'Bob'}, {'condition': 'attribute_not_exists(name)'}).then((result) => { should.exist(result); should.exist(result.Update); should.exist(result.Update.TableName); @@ -3422,104 +3361,102 @@ describe('Model', function (){ }); }); - describe('Transactions', function () { - it('Should return correct request object', function(done) { + describe('Transactions', () => { + it('Should return correct request object', (done) => { dynamoose.transaction([ - Cats.Cat.transaction.create({id: 10000}), - Cats.Cat2.transaction.update({ownerId: 1, name: 'Sara'}) - ], {returnRequest: true}).then(function(request) { + Cats.Cat.transaction.create({'id': 10000}), + Cats.Cat2.transaction.update({'ownerId': 1, 'name': 'Sara'}) + ], {'returnRequest': true}).then((request) => { should.exist(request); should.exist(request.TransactItems); - request.should.eql({'TransactItems':[{'Put':{'TableName':'test-Cat-db','Item':{'id':{'N':'10000'}},'ConditionExpression':'attribute_not_exists(id)'}},{'Update':{'TableName':'test-Cat2-db','Key':{'ownerId':{'N':'1'},'name':{'S':'Sara'}}}}]}); + request.should.eql({'TransactItems': [{'Put': {'TableName': 'test-Cat-db', 'Item': {'id': {'N': '10000'}}, 'ConditionExpression': 'attribute_not_exists(id)'}}, {'Update': {'TableName': 'test-Cat2-db', 'Key': {'ownerId': {'N': '1'}, 'name': {'S': 'Sara'}}}}]}); done(); }).catch(done); }); - it('Should return correct request object when all items are get', function(done) { + it('Should return correct request object when all items are get', (done) => { dynamoose.transaction([ Cats.Cat.transaction.get(10000), - Cats.Cat4.transaction.get(10000), - ], {returnRequest: true}).then(function(request) { + Cats.Cat4.transaction.get(10000) + ], {'returnRequest': true}).then((request) => { should.exist(request); should.exist(request.TransactItems); - request.should.eql({'TransactItems':[{'Get':{'TableName':'test-Cat-db','Key':{'id':{'N':'10000'}}}},{'Get':{'TableName':'test-Cat4-db','Key':{'id':{'N':'10000'}}}}]}); + request.should.eql({'TransactItems': [{'Get': {'TableName': 'test-Cat-db', 'Key': {'id': {'N': '10000'}}}}, {'Get': {'TableName': 'test-Cat4-db', 'Key': {'id': {'N': '10000'}}}}]}); done(); }).catch(done); }); - it('Should return correct request object when setting type to write', function(done) { + it('Should return correct request object when setting type to write', (done) => { dynamoose.transaction([ - Cats.Cat.transaction.create({id: 10000}), - Cats.Cat2.transaction.update({ownerId: 1, name: 'Sara'}) - ], {returnRequest: true, type: 'write'}).then(function(request) { + Cats.Cat.transaction.create({'id': 10000}), + Cats.Cat2.transaction.update({'ownerId': 1, 'name': 'Sara'}) + ], {'returnRequest': true, 'type': 'write'}).then((request) => { should.exist(request); should.exist(request.TransactItems); - request.should.eql({'TransactItems':[{'Put':{'TableName':'test-Cat-db','Item':{'id':{'N':'10000'}},'ConditionExpression':'attribute_not_exists(id)'}},{'Update':{'TableName':'test-Cat2-db','Key':{'ownerId':{'N':'1'},'name':{'S':'Sara'}}}}]}); + request.should.eql({'TransactItems': [{'Put': {'TableName': 'test-Cat-db', 'Item': {'id': {'N': '10000'}}, 'ConditionExpression': 'attribute_not_exists(id)'}}, {'Update': {'TableName': 'test-Cat2-db', 'Key': {'ownerId': {'N': '1'}, 'name': {'S': 'Sara'}}}}]}); done(); }).catch(done); }); - it('Should return correct request object when setting type to get', function(done) { + it('Should return correct request object when setting type to get', (done) => { dynamoose.transaction([ - Cats.Cat.transaction.create({id: 10000}), - Cats.Cat2.transaction.update({ownerId: 1, name: 'Sara'}) - ], {returnRequest: true, type: 'get'}).then(function(request) { + Cats.Cat.transaction.create({'id': 10000}), + Cats.Cat2.transaction.update({'ownerId': 1, 'name': 'Sara'}) + ], {'returnRequest': true, 'type': 'get'}).then((request) => { should.exist(request); should.exist(request.TransactItems); - request.should.eql({'TransactItems':[{'Put':{'TableName':'test-Cat-db','Item':{'id':{'N':'10000'}},'ConditionExpression':'attribute_not_exists(id)'}},{'Update':{'TableName':'test-Cat2-db','Key':{'ownerId':{'N':'1'},'name':{'S':'Sara'}}}}]}); + request.should.eql({'TransactItems': [{'Put': {'TableName': 'test-Cat-db', 'Item': {'id': {'N': '10000'}}, 'ConditionExpression': 'attribute_not_exists(id)'}}, {'Update': {'TableName': 'test-Cat2-db', 'Key': {'ownerId': {'N': '1'}, 'name': {'S': 'Sara'}}}}]}); done(); }).catch(done); }); - it('Should throw if invalid type passed in', function(done) { + it('Should throw if invalid type passed in', (done) => { dynamoose.transaction([ Cats.Cat.transaction.get(10000), - Cats.Cat4.transaction.get(10000), - ], {returnRequest: true, type: 'other'}).then(function () { + Cats.Cat4.transaction.get(10000) + ], {'returnRequest': true, 'type': 'other'}).then(() => { - }).catch(function (error) { + }).catch((error) => { should.exist(error); done(); }); }); - it('Should Properly work with read transactions', function(done) { + it('Should Properly work with read transactions', (done) => { Cats.Cat.batchPut([ - new Cats.Cat({id: '680', name: 'Oliver'}), - new Cats.Cat({id: '780', name: 'Whiskers'}) - ], function () { - return dynamoose.transaction([ - Cats.Cat.transaction.get(680), - Cats.Cat.transaction.get(780), - ]).then(function(result) { - should.exist(result); - result.length.should.equal(2); - result[0].should.be.instanceof(Cats.Cat); - result[1].should.be.instanceof(Cats.Cat); - result[0].id.should.equal(680); - result[1].id.should.equal(780); + new Cats.Cat({'id': '680', 'name': 'Oliver'}), + new Cats.Cat({'id': '780', 'name': 'Whiskers'}) + ], () => dynamoose.transaction([ + Cats.Cat.transaction.get(680), + Cats.Cat.transaction.get(780) + ]).then((result) => { + should.exist(result); + result.length.should.equal(2); + result[0].should.be.instanceof(Cats.Cat); + result[1].should.be.instanceof(Cats.Cat); + result[0].id.should.equal(680); + result[1].id.should.equal(780); - done(); - }).catch(done); - }); + done(); + }).catch(done)); }); - it('Should respond with no data', async function() { + it('Should respond with no data', async () => { let result; try { result = await dynamoose.transaction([ - Cats.Cat.transaction.create({id: 10000}), - Cats.Cat3.transaction.update({id: 1, name: 'Sara'}), - Cats.Cat.transaction.delete({id: 10000}) + Cats.Cat.transaction.create({'id': 10000}), + Cats.Cat3.transaction.update({'id': 1, 'name': 'Sara'}), + Cats.Cat.transaction.delete({'id': 10000}) ]); } catch (e) { console.error(e); @@ -3528,22 +3465,22 @@ describe('Model', function (){ should.not.exist(result); }); - it('Should throw if RAW item object passed in, and table doesn\'t exist in Dynamoose', async function() { + it('Should throw if RAW item object passed in, and table doesn\'t exist in Dynamoose', async () => { let error; try { await dynamoose.transaction([ - Cats.Cat.transaction.create({id: 30000}), - Cats.Cat3.transaction.update({id: 1, name: 'Sara'}), - Cats.Cat.transaction.delete({id: 30000}), + Cats.Cat.transaction.create({'id': 30000}), + Cats.Cat3.transaction.update({'id': 1, 'name': 'Sara'}), + Cats.Cat.transaction.delete({'id': 30000}), { - Delete: { - Key: { - id: { - S: 'helloworld' + 'Delete': { + 'Key': { + 'id': { + 'S': 'helloworld' } }, - TableName: 'MyOtherTable' + 'TableName': 'MyOtherTable' } } ]); @@ -3555,17 +3492,17 @@ describe('Model', function (){ error.message.should.eql('MyOtherTable is not a registered model. You can only use registered Dynamoose models when using a RAW transaction object.'); }); - it('Should work with conditionCheck', async function() { + it('Should work with conditionCheck', async () => { let result; try { result = await dynamoose.transaction([ - Cats.Cat.transaction.create({id: 20000}), - Cats.Cat3.transaction.update({id: 1, name: 'Sara'}), + Cats.Cat.transaction.create({'id': 20000}), + Cats.Cat3.transaction.update({'id': 1, 'name': 'Sara'}), Cats.Cat5.transaction.conditionCheck(5, { - condition: 'attribute_not_exists(owner)' + 'condition': 'attribute_not_exists(owner)' }), - Cats.Cat.transaction.delete({id: 20000}) + Cats.Cat.transaction.delete({'id': 20000}) ]); } catch (e) { console.error(e); diff --git a/test/Plugin.js b/test/Plugin.js index 28d53c4d3..74f5f821b 100644 --- a/test/Plugin.js +++ b/test/Plugin.js @@ -1,51 +1,51 @@ 'use strict'; -var dynamoose = require('../'); -dynamoose.AWS.config.update({accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-east-1'}); +const dynamoose = require('../'); +dynamoose.AWS.config.update({'accessKeyId': 'AKID', 'secretAccessKey': 'SECRET', 'region': 'us-east-1'}); dynamoose.local(); -var should = require('should'); +const should = require('should'); -describe('Plugin', function() { - var Model = dynamoose.model('Puppy', { - id: { - type: Number, - validate: function(v) { +describe('Plugin', function () { + const Model = dynamoose.model('Puppy', { + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; } }, - name: String, - owner: String, - age: { - type: Number + 'name': String, + 'owner': String, + 'age': { + 'type': Number } - }, {useDocumentTypes: true}); + }, {'useDocumentTypes': true}); this.timeout(15000); - before(function(done) { + before(function (done) { this.timeout(12000); - dynamoose.setDefaults({prefix: 'test-'}); + dynamoose.setDefaults({'prefix': 'test-'}); done(); }); - beforeEach(function(done) { + beforeEach((done) => { Model.clearAllPlugins(); done(); }); - after(function(done) { + after((done) => { delete dynamoose.models['test-Cat']; done(); }); - it('Should create simple plugin', function(done) { + it('Should create simple plugin', (done) => { Model.$__.plugins.length.should.eql(0); - Model.plugin(function(obj) { + Model.plugin((obj) => { should.exist(obj.on); should.exist(obj.setName); should.exist(obj.setDescription); @@ -56,10 +56,10 @@ describe('Plugin', function() { done(); }); - it('Should delete all plugins after calling Model.clearAllPlugins()', function(done) { + it('Should delete all plugins after calling Model.clearAllPlugins()', (done) => { Model.$__.plugins.length.should.eql(0); - Model.plugin(function(obj) { + Model.plugin((obj) => { should.exist(obj.on); should.exist(obj.setName); should.exist(obj.setDescription); @@ -74,11 +74,11 @@ describe('Plugin', function() { done(); }); - it('Should call plugin:register listener when plugin is registered', function(done) { - var counter = 0; + it('Should call plugin:register listener when plugin is registered', (done) => { + let counter = 0; - Model.plugin(function(obj) { - obj.on('plugin:register', function() { + Model.plugin((obj) => { + obj.on('plugin:register', () => { counter += 1; }); }); @@ -88,19 +88,19 @@ describe('Plugin', function() { done(); }); - it('Should call plugin:register listener when new plugin is registered', function(done) { - var counter = 0; + it('Should call plugin:register listener when new plugin is registered', (done) => { + let counter = 0; - Model.plugin(function(obj) { - obj.on('plugin:register', function() { + Model.plugin((obj) => { + obj.on('plugin:register', () => { counter += 1; }); }); counter.should.eql(1); // plugin 1 post - Model.plugin(function(obj) { - obj.on('plugin:register', function() { + Model.plugin((obj) => { + obj.on('plugin:register', () => { }); }); @@ -109,18 +109,18 @@ describe('Plugin', function() { done(); }); - it('Shouldn\'t fail if no function passed into .on function', function(done) { + it('Shouldn\'t fail if no function passed into .on function', (done) => { - Model.plugin(function(obj) { + Model.plugin((obj) => { obj.on('plugin:register'); }); done(); }); - it('Should pass in details into "plugin:register" on function', function(done) { - Model.plugin(function(obj) { - obj.on('plugin:register', function (obj) { + it('Should pass in details into "plugin:register" on function', (done) => { + Model.plugin((obj) => { + obj.on('plugin:register', (obj) => { should.exist(obj.event); should.exist(obj.model); should.exist(obj.modelName); @@ -133,29 +133,29 @@ describe('Plugin', function() { done(); }); - it('Plugin Options should equal empty object if not defined', function(done) { - Model.plugin(function(obj) { - obj.on('plugin:register', function (obj) { + it('Plugin Options should equal empty object if not defined', (done) => { + Model.plugin((obj) => { + obj.on('plugin:register', (obj) => { obj.event.pluginOptions.should.deep.eql({}); }); }); done(); }); - it('Plugin Options should equal object passed in', function(done) { - Model.plugin(function(obj) { - obj.on('plugin:register', function (obj) { - obj.event.pluginOptions.should.deep.eql({username: 'test'}); + it('Plugin Options should equal object passed in', (done) => { + Model.plugin((obj) => { + obj.on('plugin:register', (obj) => { + obj.event.pluginOptions.should.deep.eql({'username': 'test'}); }); - }, {username: 'test'}); + }, {'username': 'test'}); done(); }); - it('Type of "*" should catch all events emited from Dynamoose', function(done) { - var counter = 0; + it('Type of "*" should catch all events emited from Dynamoose', (done) => { + let counter = 0; - Model.plugin(function(obj) { - obj.on('*', function () { + Model.plugin((obj) => { + obj.on('*', () => { counter += 1; }); }); @@ -165,11 +165,11 @@ describe('Plugin', function() { done(); }); - it('No type passed in should catch all events emited from Dynamoose', function(done) { - var counter = 0; + it('No type passed in should catch all events emited from Dynamoose', (done) => { + let counter = 0; - Model.plugin(function(obj) { - obj.on(function () { + Model.plugin((obj) => { + obj.on(() => { counter += 1; }); }); @@ -179,19 +179,19 @@ describe('Plugin', function() { done(); }); - it('Should allow sub-plugins or registration of plugins within plugin', function(done) { - var counter = 0; + it('Should allow sub-plugins or registration of plugins within plugin', (done) => { + let counter = 0; - var pluginB = function(plugin) { + const pluginB = function (plugin) { plugin.setName('Plugin B'); - plugin.on('plugin', 'init', function () { + plugin.on('plugin', 'init', () => { counter += 1; }); }; - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('plugin', 'init', function (obj) { + plugin.on('plugin', 'init', (obj) => { obj.actions.registerPlugin(pluginB); }); }; @@ -205,12 +205,12 @@ describe('Plugin', function() { done(); }); - it('Should work with model:scan', function(done) { - var counter = 0; + it('Should work with model:scan', (done) => { + let counter = 0; - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:scan', function () { + plugin.on('model:scan', () => { counter += 1; }); }; @@ -218,7 +218,7 @@ describe('Plugin', function() { Model.plugin(pluginA); - Model.scan({}).exec(function() { + Model.scan({}).exec(() => { Model.$__.plugins.length.should.eql(1); counter.should.eql(4); @@ -227,23 +227,21 @@ describe('Plugin', function() { }); - it('Should continue for with model:scan request:pre', function(done) { + it('Should continue for with model:scan request:pre', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:scan', 'request:pre', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({resolve: 'Test'}); - }, 500); - }); - }); + plugin.on('model:scan', 'request:pre', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'resolve': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.scan({}).exec(function(err, result) { + Model.scan({}).exec((err, result) => { result.should.eql('Test'); done(); @@ -251,23 +249,21 @@ describe('Plugin', function() { }); - it('Should not continue for with model:scan request:pre', function(done) { + it('Should not continue for with model:scan request:pre', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:scan', 'request:pre', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({reject: 'Test'}); - }, 500); - }); - }); + plugin.on('model:scan', 'request:pre', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'reject': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.scan({}).exec(function(err) { + Model.scan({}).exec((err) => { err.should.eql('Test'); done(); @@ -275,23 +271,21 @@ describe('Plugin', function() { }); - it('Should continue for with model:scan request:post', function(done) { + it('Should continue for with model:scan request:post', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:scan', 'request:post', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({resolve: 'Test'}); - }, 500); - }); - }); + plugin.on('model:scan', 'request:post', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'resolve': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.scan({}).exec(function(err, result) { + Model.scan({}).exec((err, result) => { result.should.eql('Test'); done(); @@ -299,23 +293,21 @@ describe('Plugin', function() { }); - it('Should continue for with model:scan request:post', function(done) { + it('Should continue for with model:scan request:post', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:scan', 'request:post', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({reject: 'Test'}); - }, 500); - }); - }); + plugin.on('model:scan', 'request:post', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'reject': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.scan({}).exec(function(err) { + Model.scan({}).exec((err) => { err.should.eql('Test'); done(); @@ -323,12 +315,12 @@ describe('Plugin', function() { }); - it('Should work with model:query', function(done) { - var counter = 0; + it('Should work with model:query', (done) => { + let counter = 0; - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:query', function () { + plugin.on('model:query', () => { counter += 1; }); }; @@ -336,7 +328,7 @@ describe('Plugin', function() { Model.plugin(pluginA); - Model.query('id').eq(1).exec(function() { + Model.query('id').eq(1).exec(() => { Model.$__.plugins.length.should.eql(1); counter.should.eql(4); @@ -345,23 +337,21 @@ describe('Plugin', function() { }); - it('Should continue for with model:query request:pre', function(done) { + it('Should continue for with model:query request:pre', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:query', 'request:pre', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({resolve: 'Test'}); - }, 500); - }); - }); + plugin.on('model:query', 'request:pre', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'resolve': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.query('id').eq(1).exec(function(err, result) { + Model.query('id').eq(1).exec((err, result) => { result.should.eql('Test'); done(); @@ -369,23 +359,21 @@ describe('Plugin', function() { }); - it('Should not continue for with model:query request:pre', function(done) { + it('Should not continue for with model:query request:pre', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:query', 'request:pre', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({reject: 'Test'}); - }, 500); - }); - }); + plugin.on('model:query', 'request:pre', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'reject': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.query('id').eq(1).exec(function(err) { + Model.query('id').eq(1).exec((err) => { err.should.eql('Test'); done(); @@ -393,23 +381,21 @@ describe('Plugin', function() { }); - it('Should continue for with model:query request:post', function(done) { + it('Should continue for with model:query request:post', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:query', 'request:post', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({resolve: 'Test'}); - }, 500); - }); - }); + plugin.on('model:query', 'request:post', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'resolve': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.query('id').eq(1).exec(function(err, result) { + Model.query('id').eq(1).exec((err, result) => { result.should.eql('Test'); done(); @@ -417,23 +403,21 @@ describe('Plugin', function() { }); - it('Should not continue for with model:query request:post', function(done) { + it('Should not continue for with model:query request:post', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:query', 'request:post', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({reject: 'Test'}); - }, 500); - }); - }); + plugin.on('model:query', 'request:post', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'reject': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.query('id').eq(1).exec(function(err) { + Model.query('id').eq(1).exec((err) => { err.should.eql('Test'); done(); @@ -441,12 +425,12 @@ describe('Plugin', function() { }); - it('Should work with model:get', function(done) { - var counter = 0; + it('Should work with model:get', (done) => { + let counter = 0; - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:get', function () { + plugin.on('model:get', () => { counter += 1; }); }; @@ -454,7 +438,7 @@ describe('Plugin', function() { Model.plugin(pluginA); - Model.get('', function() { + Model.get('', () => { Model.$__.plugins.length.should.eql(1); counter.should.eql(3); @@ -463,23 +447,21 @@ describe('Plugin', function() { }); - it('Should continue for model:get request:pre', function(done) { + it('Should continue for model:get request:pre', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:get', 'request:pre', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({resolve: 'Test'}); - }, 500); - }); - }); + plugin.on('model:get', 'request:pre', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'resolve': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.get('', function(err, result) { + Model.get('', (err, result) => { result.should.eql('Test'); done(); @@ -487,23 +469,21 @@ describe('Plugin', function() { }); - it('Should not continue for model:get request:pre', function(done) { + it('Should not continue for model:get request:pre', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:get', 'request:pre', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({reject: 'Test'}); - }, 500); - }); - }); + plugin.on('model:get', 'request:pre', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'reject': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.get('', function(err) { + Model.get('', (err) => { err.should.eql('Test'); done(); @@ -511,23 +491,21 @@ describe('Plugin', function() { }); - it('Should continue for model:get request:post', function(done) { + it('Should continue for model:get request:post', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:get', 'request:post', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({resolve: 'Test'}); - }, 500); - }); - }); + plugin.on('model:get', 'request:post', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'resolve': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.get('', function(err, result) { + Model.get('', (err, result) => { result.should.eql('Test'); done(); @@ -535,23 +513,21 @@ describe('Plugin', function() { }); - it('Should continue for model:get request:post', function(done) { + it('Should continue for model:get request:post', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:get', 'request:post', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({reject: 'Test'}); - }, 500); - }); - }); + plugin.on('model:get', 'request:post', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'reject': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - Model.get('', function(err) { + Model.get('', (err) => { err.should.eql('Test'); done(); @@ -559,12 +535,12 @@ describe('Plugin', function() { }); - it('Should work with model:put', function(done) { - var counter = 0; + it('Should work with model:put', (done) => { + let counter = 0; - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:put', function () { + plugin.on('model:put', () => { counter += 1; }); }; @@ -572,15 +548,15 @@ describe('Plugin', function() { Model.plugin(pluginA); - var myItem = new Model( + const myItem = new Model( { - id: 1, - name: 'Lucky', - owner: 'Bob', - age: 2 + 'id': 1, + 'name': 'Lucky', + 'owner': 'Bob', + 'age': 2 } ); - myItem.save(function() { + myItem.save(() => { Model.$__.plugins.length.should.eql(1); counter.should.eql(3); @@ -589,31 +565,29 @@ describe('Plugin', function() { }); - it('Should continue for model:put request:pre', function(done) { + it('Should continue for model:put request:pre', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:put', 'request:pre', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({resolve: 'Test'}); - }, 500); - }); - }); + plugin.on('model:put', 'request:pre', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'resolve': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - var myItem = new Model( + const myItem = new Model( { - id: 1, - name: 'Lucky', - owner: 'Bob', - age: 2 + 'id': 1, + 'name': 'Lucky', + 'owner': 'Bob', + 'age': 2 } ); - myItem.save(function(err, result) { + myItem.save((err, result) => { result.should.eql('Test'); done(); @@ -621,31 +595,29 @@ describe('Plugin', function() { }); - it('Should not continue for model:put request:pre on adding a model', function(done) { + it('Should not continue for model:put request:pre on adding a model', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:put', 'request:pre', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({reject: 'Test'}); - }, 500); - }); - }); + plugin.on('model:put', 'request:pre', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'reject': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - var myItem = new Model( + const myItem = new Model( { - id: 1, - name: 'Lucky', - owner: 'Bob', - age: 2 + 'id': 1, + 'name': 'Lucky', + 'owner': 'Bob', + 'age': 2 } ); - myItem.save(function(err) { + myItem.save((err) => { err.should.eql('Test'); done(); @@ -653,31 +625,29 @@ describe('Plugin', function() { }); - it('Should continue for model:put request:post', function(done) { + it('Should continue for model:put request:post', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:put', 'request:post', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({resolve: 'Test'}); - }, 500); - }); - }); + plugin.on('model:put', 'request:post', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'resolve': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - var myItem = new Model( + const myItem = new Model( { - id: 1, - name: 'Lucky', - owner: 'Bob', - age: 2 + 'id': 1, + 'name': 'Lucky', + 'owner': 'Bob', + 'age': 2 } ); - myItem.save(function(err, result) { + myItem.save((err, result) => { result.should.eql('Test'); done(); @@ -685,31 +655,29 @@ describe('Plugin', function() { }); - it('Should not continue for model:put request:post', function(done) { + it('Should not continue for model:put request:post', (done) => { - var pluginA = function(plugin) { + const pluginA = function (plugin) { plugin.setName('Plugin A'); - plugin.on('model:put', 'request:post', function () { - return new Promise(function(resolve) { - setTimeout(() => { - resolve({reject: 'Test'}); - }, 500); - }); - }); + plugin.on('model:put', 'request:post', () => new Promise((resolve) => { + setTimeout(() => { + resolve({'reject': 'Test'}); + }, 500); + })); }; Model.plugin(pluginA); - var myItem = new Model( + const myItem = new Model( { - id: 1, - name: 'Lucky', - owner: 'Bob', - age: 2 + 'id': 1, + 'name': 'Lucky', + 'owner': 'Bob', + 'age': 2 } ); - myItem.save(function(err) { + myItem.save((err) => { err.should.eql('Test'); done(); diff --git a/test/Query.js b/test/Query.js index 0cfa0dea6..b0e4ed3fb 100644 --- a/test/Query.js +++ b/test/Query.js @@ -1,93 +1,99 @@ 'use strict'; -var dynamoose = require('../'); +const dynamoose = require('../'); dynamoose.AWS.config.update({ - accessKeyId: 'AKID', - secretAccessKey: 'SECRET', - region: 'us-east-1' + 'accessKeyId': 'AKID', + 'secretAccessKey': 'SECRET', + 'region': 'us-east-1' }); dynamoose.local(); -var Schema = dynamoose.Schema; +const Schema = dynamoose.Schema; -var should = require('should'); +const should = require('should'); -describe('Query', function (){ +describe('Query', function () { this.timeout(10000); - before(function (done) { - - dynamoose.setDefaults({ prefix: '', suffix: '' }); - - var dogSchema = new Schema({ - ownerId: { - type: Number, - validate: function(v) { return v > 0; }, - hashKey: true, - index: [{ - global: true, - rangeKey: 'color', - name: 'ColorRangeIndex', - project: true, // ProjectionType: ALL - },{ - global: true, - rangeKey: 'breed', - name: 'BreedRangeIndex', - project: true, // ProjectionType: ALL - }] + before((done) => { + + dynamoose.setDefaults({'prefix': '', 'suffix': ''}); + + const dogSchema = new Schema({ + 'ownerId': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'hashKey': true, + 'index': [ + { + 'global': true, + 'rangeKey': 'color', + 'name': 'ColorRangeIndex', + 'project': true // ProjectionType: ALL + }, { + 'global': true, + 'rangeKey': 'breed', + 'name': 'BreedRangeIndex', + 'project': true // ProjectionType: ALL + } + ] }, - breed: { - type: String, - required: true, - index: { - global: true, - rangeKey: 'ownerId', - name: 'BreedIndex', - project: true, // ProjectionType: ALL - throughput: 5 // read and write are both 5 + 'breed': { + 'type': String, + 'required': true, + 'index': { + 'global': true, + 'rangeKey': 'ownerId', + 'name': 'BreedIndex', + 'project': true, // ProjectionType: ALL + 'throughput': 5 // read and write are both 5 } }, - origin: { - type: String, - index: true // name: originLocalIndex, ProjectionType: ALL + 'origin': { + 'type': String, + 'index': true // name: originLocalIndex, ProjectionType: ALL }, - name: { - type: String, - rangeKey: true, - index: true // name: nameLocalIndex, ProjectionType: ALL + 'name': { + 'type': String, + 'rangeKey': true, + 'index': true // name: nameLocalIndex, ProjectionType: ALL }, - color: { - type: String, - default: 'Brown', - index: [{ // name: colorLocalIndex - project: ['name'] // ProjectionType: INCLUDE - },{ // name: colorGlobalIndex, no ragne key - global: true, - project: ['name'] // ProjectionType: INCLUDE - }] + 'color': { + 'type': String, + 'default': 'Brown', + 'index': [ + { // name: colorLocalIndex + 'project': ['name'] // ProjectionType: INCLUDE + }, { // name: colorGlobalIndex, no ragne key + 'global': true, + 'project': ['name'] // ProjectionType: INCLUDE + } + ] }, - siblings: { - type: 'list', - list: [ { - type: String - } ] + 'siblings': { + 'type': 'list', + 'list': [ + { + 'type': String + } + ] }, - age: { - type: Number + 'age': { + 'type': Number } }); - var Dog = dynamoose.model('Dog', dogSchema); + const Dog = dynamoose.model('Dog', dogSchema); function addDogs (dogs) { - if(dogs.length <= 0) { + if (dogs.length <= 0) { return done(); } - var dog = new Dog(dogs.pop()); - dog.save(function (err) { + const dog = new Dog(dogs.pop()); + dog.save((err) => { if (err) { return done(err); } @@ -96,39 +102,39 @@ describe('Query', function (){ } addDogs([ - {ownerId:1, name: 'Foxy Lady', breed: 'Jack Russell Terrier', color: 'White, Brown and Black', siblings: ['Quincy', 'Princes'], age: 2}, - {ownerId:2, name: 'Quincy', breed: 'Jack Russell Terrier', color: 'White and Brown', siblings: ['Foxy Lady', 'Princes'], age: 3}, - {ownerId:2, name: 'Princes', breed: 'Jack Russell Terrier', color: 'White and Brown', siblings: ['Foxy Lady', 'Quincy'], age: 6}, - {ownerId:3, name: 'Toto', breed: 'Terrier', color: 'Brown', age: 1}, - {ownerId:4, name: 'Oddie', breed: 'beagle', color: 'Tan', age: 2}, - {ownerId:5, name: 'Pluto', breed: 'unknown', color: 'Mustard', age: 4}, - {ownerId:6, name: 'Brian Griffin', breed: 'unknown', color: 'White', age: 5}, - {ownerId:7, name: 'Scooby Doo', breed: 'Great Dane', age: 2}, - {ownerId:8, name: 'Blue', breed: 'unknown', color: 'Blue', age: 1}, - {ownerId:9, name: 'Lady', breed: ' Cocker Spaniel', age: 6}, - {ownerId:10, name: 'Copper', breed: 'Hound', age: 8}, - {ownerId:11, name: 'Old Yeller', breed: 'unknown', color: 'Tan', age: 1}, - {ownerId:12, name: 'Hooch', breed: 'Dogue de Bordeaux', color: 'Brown', age: 3}, - {ownerId:13, name: 'Rin Tin Tin', breed: 'German Shepherd', age: 5}, - {ownerId:14, name: 'Benji', breed: 'unknown', age: 1}, - {ownerId:15, name: 'Wishbone', breed: 'Jack Russell Terrier', color: 'White', age: 2}, - {ownerId:16, name: 'Marley', breed: 'Labrador Retriever', color: 'Yellow', age: 9}, - {ownerId:17, name: 'Beethoven', breed: 'St. Bernard', age: 3}, - {ownerId:18, name: 'Lassie', breed: 'Collie', color: 'tan and white', age: 4}, - {ownerId:19, name: 'Snoopy', breed: 'beagle', color: 'black and white', age: 6}, - {ownerId:20, name: 'Max', breed: 'Westie', age: 7, origin: 'Scotland'}, - {ownerId:20, name: 'Gigi', breed: 'Spaniel', color: 'Chocolate', age: 1, origin: 'Great Britain'}, - {ownerId:20, name: 'Mimo', breed: 'Boxer', color: 'Chocolate', age: 2, origin: 'Germany'}, - {ownerId:20, name: 'Bepo', breed: 'French Bulldog', color: 'Grey', age: 4, origin: 'France'}, + {'ownerId': 1, 'name': 'Foxy Lady', 'breed': 'Jack Russell Terrier', 'color': 'White, Brown and Black', 'siblings': ['Quincy', 'Princes'], 'age': 2}, + {'ownerId': 2, 'name': 'Quincy', 'breed': 'Jack Russell Terrier', 'color': 'White and Brown', 'siblings': ['Foxy Lady', 'Princes'], 'age': 3}, + {'ownerId': 2, 'name': 'Princes', 'breed': 'Jack Russell Terrier', 'color': 'White and Brown', 'siblings': ['Foxy Lady', 'Quincy'], 'age': 6}, + {'ownerId': 3, 'name': 'Toto', 'breed': 'Terrier', 'color': 'Brown', 'age': 1}, + {'ownerId': 4, 'name': 'Oddie', 'breed': 'beagle', 'color': 'Tan', 'age': 2}, + {'ownerId': 5, 'name': 'Pluto', 'breed': 'unknown', 'color': 'Mustard', 'age': 4}, + {'ownerId': 6, 'name': 'Brian Griffin', 'breed': 'unknown', 'color': 'White', 'age': 5}, + {'ownerId': 7, 'name': 'Scooby Doo', 'breed': 'Great Dane', 'age': 2}, + {'ownerId': 8, 'name': 'Blue', 'breed': 'unknown', 'color': 'Blue', 'age': 1}, + {'ownerId': 9, 'name': 'Lady', 'breed': ' Cocker Spaniel', 'age': 6}, + {'ownerId': 10, 'name': 'Copper', 'breed': 'Hound', 'age': 8}, + {'ownerId': 11, 'name': 'Old Yeller', 'breed': 'unknown', 'color': 'Tan', 'age': 1}, + {'ownerId': 12, 'name': 'Hooch', 'breed': 'Dogue de Bordeaux', 'color': 'Brown', 'age': 3}, + {'ownerId': 13, 'name': 'Rin Tin Tin', 'breed': 'German Shepherd', 'age': 5}, + {'ownerId': 14, 'name': 'Benji', 'breed': 'unknown', 'age': 1}, + {'ownerId': 15, 'name': 'Wishbone', 'breed': 'Jack Russell Terrier', 'color': 'White', 'age': 2}, + {'ownerId': 16, 'name': 'Marley', 'breed': 'Labrador Retriever', 'color': 'Yellow', 'age': 9}, + {'ownerId': 17, 'name': 'Beethoven', 'breed': 'St. Bernard', 'age': 3}, + {'ownerId': 18, 'name': 'Lassie', 'breed': 'Collie', 'color': 'tan and white', 'age': 4}, + {'ownerId': 19, 'name': 'Snoopy', 'breed': 'beagle', 'color': 'black and white', 'age': 6}, + {'ownerId': 20, 'name': 'Max', 'breed': 'Westie', 'age': 7, 'origin': 'Scotland'}, + {'ownerId': 20, 'name': 'Gigi', 'breed': 'Spaniel', 'color': 'Chocolate', 'age': 1, 'origin': 'Great Britain'}, + {'ownerId': 20, 'name': 'Mimo', 'breed': 'Boxer', 'color': 'Chocolate', 'age': 2, 'origin': 'Germany'}, + {'ownerId': 20, 'name': 'Bepo', 'breed': 'French Bulldog', 'color': 'Grey', 'age': 4, 'origin': 'France'} ]); }); - after(function (done) { - var Dog = dynamoose.model('Dog'); + after((done) => { + const Dog = dynamoose.model('Dog'); - Dog.$__.table.delete(function (err) { - if(err) { + Dog.$__.table.delete((err) => { + if (err) { done(err); } delete dynamoose.models.Dog; @@ -137,10 +143,10 @@ describe('Query', function (){ }); - it('Basic Query', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('ownerId').eq(2).exec(function (err, dogs) { + Dog.query('ownerId').eq(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(2); done(); @@ -148,10 +154,10 @@ describe('Query', function (){ }); - it('Basic Query One', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query One', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.queryOne('ownerId').eq(1).exec(function (err, oneDog) { + Dog.queryOne('ownerId').eq(1).exec((err, oneDog) => { should.not.exist(err); should.exist(oneDog); oneDog.ownerId.should.eql(1); @@ -159,10 +165,10 @@ describe('Query', function (){ }); }); - it('Basic Query on Secondary Global Index', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on Secondary Global Index', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('breed').eq('Jack Russell Terrier').exec(function (err, dogs) { + Dog.query('breed').eq('Jack Russell Terrier').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); dogs[0].ownerId.should.eql(1); @@ -170,30 +176,30 @@ describe('Query', function (){ }); }); - it('Query on Secondary Global Index with range - no results', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query on Secondary Global Index with range - no results', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('breed').eq('Jack Russell Terrier').where('ownerId').eq(4).exec(function (err, dogs) { + Dog.query('breed').eq('Jack Russell Terrier').where('ownerId').eq(4).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(0); done(); }); }); - it('Query on Secondary Global Index with range', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query on Secondary Global Index with range', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('breed').eq('unknown').where('ownerId').lt(8).exec(function (err, dogs) { + Dog.query('breed').eq('unknown').where('ownerId').lt(8).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(2); done(); }); }); - it('Query on Secondary Global Index with same hashKey', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query on Secondary Global Index with same hashKey', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('ownerId').eq(20).where('color').beginsWith('Choc').exec(function (err, dogs) { + Dog.query('ownerId').eq(20).where('color').beginsWith('Choc').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(2); dogs[0].name.should.eql('Gigi'); @@ -202,10 +208,10 @@ describe('Query', function (){ }); }); - it('Query on Secondary Global Index with same hashKey and 2nd in index list', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query on Secondary Global Index with same hashKey and 2nd in index list', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('ownerId').using('BreedRangeIndex').eq(20).where('breed').beginsWith('Sp').exec(function (err, dogs) { + Dog.query('ownerId').using('BreedRangeIndex').eq(20).where('breed').beginsWith('Sp').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); dogs[0].name.should.eql('Gigi'); @@ -213,17 +219,17 @@ describe('Query', function (){ }); }); - it('Query with Secondary Local Index as range', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query with Secondary Local Index as range', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('ownerId').eq(20).where('origin').beginsWith('G').exec(function (err, dogs) { + Dog.query('ownerId').eq(20).where('origin').beginsWith('G').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(2); done(); }); }); - it('where() must follow eq()', async function () { + it('where() must follow eq()', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -238,7 +244,7 @@ describe('Query', function (){ error.message.should.eql('Invalid Query state: where() must follow eq()'); }); - it('filter() must follow comparison', async function () { + it('filter() must follow comparison', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -253,7 +259,7 @@ describe('Query', function (){ error.message.should.eql('Invalid Query state: filter() must follow comparison'); }); - it('eq must follow query()', async function () { + it('eq must follow query()', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -268,7 +274,7 @@ describe('Query', function (){ error.message.should.eql('Invalid Query state: eq must follow query()'); }); - it('Should throw first error', async function () { + it('Should throw first error', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -283,10 +289,10 @@ describe('Query', function (){ error.message.should.eql('Invalid Query state: eq must follow query()'); }); - it('Basic Query on SGI descending', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI descending', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('breed').eq('Jack Russell Terrier').descending().exec(function (err, dogs) { + Dog.query('breed').eq('Jack Russell Terrier').descending().exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); dogs[0].ownerId.should.eql(15); @@ -294,10 +300,10 @@ describe('Query', function (){ }); }); - it('Basic Query on SGI ascending', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI ascending', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('breed').eq('Jack Russell Terrier').ascending().exec(function (err, dogs) { + Dog.query('breed').eq('Jack Russell Terrier').ascending().exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); dogs[0].ownerId.should.eql(1); @@ -306,10 +312,10 @@ describe('Query', function (){ }); - it('Basic Query on SGI limit 1', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI limit 1', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('breed').eq('Jack Russell Terrier').limit(1).exec(function (err, dogs) { + Dog.query('breed').eq('Jack Russell Terrier').limit(1).exec((err, dogs) => { should.not.exist(err); should.exist(dogs.lastKey); dogs.length.should.eql(1); @@ -318,14 +324,14 @@ describe('Query', function (){ }); }); - it('Basic Query on SGI startAt key', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI startAt key', (done) => { + const Dog = dynamoose.model('Dog'); - var startKey = { breed: { S: 'Jack Russell Terrier' }, - ownerId: { N: '1' }, - name: { S: 'Foxy Lady' } }; + const startKey = {'breed': {'S': 'Jack Russell Terrier'}, + 'ownerId': {'N': '1'}, + 'name': {'S': 'Foxy Lady'}}; - Dog.query('breed').eq('Jack Russell Terrier').startAt(startKey).limit(1).exec(function (err, dogs) { + Dog.query('breed').eq('Jack Russell Terrier').startAt(startKey).limit(1).exec((err, dogs) => { should.not.exist(err); should.exist(dogs.lastKey); dogs.length.should.eql(1); @@ -334,10 +340,10 @@ describe('Query', function (){ }); }); - it('Basic Query on SGI with attributes', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with attributes', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('breed').eq('Jack Russell Terrier').attributes(['name']).exec(function (err, dogs) { + Dog.query('breed').eq('Jack Russell Terrier').attributes(['name']).exec((err, dogs) => { should.not.exist(err); should.not.exist(dogs.lastKey); dogs.length.should.eql(4); @@ -347,23 +353,23 @@ describe('Query', function (){ }); }); - it('Basic Query with consistent read', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query with consistent read', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.query('ownerId').eq(2).consistent().exec(function (err, dogs) { + Dog.query('ownerId').eq(2).consistent().exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(2); done(); }); }); - it('Basic Query on SGI with filter contains', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter contains', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('Jack Russell Terrier') .where('ownerId').eq(1) .filter('color').contains('Black').exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(1); dogs[0].ownerId.should.eql(1); done(); @@ -372,13 +378,13 @@ describe('Query', function (){ }); - it('Basic Query on SGI with filter contains on list', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter contains on list', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('Jack Russell Terrier') .where('ownerId').eq(2) .filter('siblings').contains('Quincy').exec() - .then(function (dogs) { + .then((dogs) => { // console.log('The dogs', dogs); dogs.length.should.eql(1); dogs[0].ownerId.should.eql(2); @@ -388,37 +394,37 @@ describe('Query', function (){ }); - it('Basic Query on SGI with filter null', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter null', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .filter('color').not().null().exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(5); done(); }) .catch(done); }); - it('Basic Query on SGI with filter not null', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter not null', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .filter('color').null().exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(0); done(); }) .catch(done); }); - it('Basic Query on SGI with filter le', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter le', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .where('ownerId').le(11) .exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(4); dogs[dogs.length - 1].ownerId.should.eql(11); done(); @@ -426,13 +432,13 @@ describe('Query', function (){ .catch(done); }); - it('Basic Query on SGI with filter not le', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter not le', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .where('ownerId').not().le(11) .exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(1); dogs[0].ownerId.should.eql(14); done(); @@ -440,13 +446,13 @@ describe('Query', function (){ .catch(done); }); - it('Basic Query on SGI with filter ge', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter ge', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .where('ownerId').ge(11) .exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(2); dogs[0].ownerId.should.eql(11); done(); @@ -454,13 +460,13 @@ describe('Query', function (){ .catch(done); }); - it('Basic Query on SGI with filter not ge', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter not ge', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .where('ownerId').not().ge(11) .exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(3); dogs[0].ownerId.should.eql(5); done(); @@ -468,13 +474,13 @@ describe('Query', function (){ .catch(done); }); - it('Basic Query on SGI with filter gt', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter gt', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .where('ownerId').gt(11) .exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(1); dogs[0].ownerId.should.eql(14); done(); @@ -482,13 +488,13 @@ describe('Query', function (){ .catch(done); }); - it('Basic Query on SGI with filter not gt', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter not gt', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .where('ownerId').not().gt(11) .exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(4); dogs[0].ownerId.should.eql(5); done(); @@ -496,15 +502,15 @@ describe('Query', function (){ .catch(done); }); - it('Basic Query on SGI with filter not eq and not lt', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter not eq and not lt', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .where('ownerId').not().lt(10) .and() .filter('color').not().eq('Brown') .exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(1); dogs[0].ownerId.should.eql(11); done(); @@ -512,14 +518,14 @@ describe('Query', function (){ .catch(done); }); - it('Basic Query on SGI with filter not contains or beginsWith', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter not contains or beginsWith', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('Jack Russell Terrier') .filter('color').not().contains('Brown') .or() .filter('name').beginsWith('Q').exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(2); done(); }) @@ -527,7 +533,7 @@ describe('Query', function (){ }); - it('beginsWith() cannot follow not()', async function () { + it('beginsWith() cannot follow not()', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -542,12 +548,12 @@ describe('Query', function (){ error.message.should.eql('Invalid Query state: beginsWith() cannot follow not()'); }); - it('Basic Query on SGI with filter between', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter between', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('Jack Russell Terrier') - .filter('age').between(5,7) - .exec(function (err, dogs) { + .filter('age').between(5, 7) + .exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); dogs[0].ownerId.should.eql(2); @@ -555,12 +561,12 @@ describe('Query', function (){ }); }); - it('between() cannot follow not()', async function () { + it('between() cannot follow not()', async () => { const Dog = dynamoose.model('Dog'); let error; try { - await Dog.query('breed').eq('Jack Russell Terrier').filter('age').not().between(5,7).exec(); + await Dog.query('breed').eq('Jack Russell Terrier').filter('age').not().between(5, 7).exec(); } catch (e) { error = e; } @@ -570,12 +576,12 @@ describe('Query', function (){ error.message.should.eql('Invalid Query state: between() cannot follow not()'); }); - it('Basic Query on SGI with filter in', function (done) { - var Dog = dynamoose.model('Dog'); + it('Basic Query on SGI with filter in', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('Jack Russell Terrier') .filter('color').in(['White and Brown', 'White']) - .exec(function (err, dogs) { + .exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(3); dogs[0].ownerId.should.eql(2); @@ -583,7 +589,7 @@ describe('Query', function (){ }); }); - it('in() cannot follow not()', async function () { + it('in() cannot follow not()', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -598,25 +604,25 @@ describe('Query', function (){ error.message.should.eql('Invalid Query state: in() cannot follow not()'); }); - it('Query.count', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query.count', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('ownerId').eq(20).count().all().exec() - .then(function (count) { + .then((count) => { count.should.eql(4); done(); }) .catch(done); }); - it('Query.counts', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query.counts', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('breed').eq('unknown') .and() .filter('color').not().eq('Brown') .counts().all().exec() - .then(function (counts) { + .then((counts) => { counts.scannedCount.should.eql(5); counts.count.should.eql(4); done(); @@ -624,22 +630,22 @@ describe('Query', function (){ .catch(done); }); - it('Query.all', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query.all', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('ownerId').eq(20).limit(2).all().exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(4); done(); }) .catch(done); }); - it('Query.all(1, 3)', function (done) { - var Dog = dynamoose.model('Dog'); + it('Query.all(1, 3)', (done) => { + const Dog = dynamoose.model('Dog'); Dog.query('ownerId').eq(20).limit(1).all(1000, 3).exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(3); dogs.timesQueried.should.eql(3); done(); @@ -647,102 +653,104 @@ describe('Query', function (){ .catch(done); }); - it('Should allow multiple indexes and query correctly', function (done) { - var schema = new dynamoose.Schema({ - id: { - type: String, - hashKey: true, - required: true + it('Should allow multiple indexes and query correctly', (done) => { + const schema = new dynamoose.Schema({ + 'id': { + 'type': String, + 'hashKey': true, + 'required': true }, - orgId: { - type: String, - index: [{ - global : true, - name : 'OrganizationCreateAtIndex', - rangeKey : 'createdAt', - throughput: 1 - }, { - global : true, - name : 'OrganizationExpectedArriveAtIndex', - rangeKey : 'expectedArriveAt', - throughput: 1 - }], - required: true, + 'orgId': { + 'type': String, + 'index': [ + { + 'global': true, + 'name': 'OrganizationCreateAtIndex', + 'rangeKey': 'createdAt', + 'throughput': 1 + }, { + 'global': true, + 'name': 'OrganizationExpectedArriveAtIndex', + 'rangeKey': 'expectedArriveAt', + 'throughput': 1 + } + ], + 'required': true }, - expectedArriveAt: Date - },{ - throughput: 1, - timestamps: true + 'expectedArriveAt': Date + }, { + 'throughput': 1, + 'timestamps': true }); - var Log = dynamoose.model('Log-1', schema); + const Log = dynamoose.model('Log-1', schema); - var log1 = new Log({id: 'test1', orgId: 'org1', expectedArriveAt: Date.now()}); - log1.save(function() { + const log1 = new Log({'id': 'test1', 'orgId': 'org1', 'expectedArriveAt': Date.now()}); + log1.save(() => { Log.query('orgId').eq('org1') - .where('expectedArriveAt').lt( new Date() ) + .where('expectedArriveAt').lt(new Date()) .exec() - .then(function(res){ + .then((res) => { res.length.should.eql(1); Log.query('orgId').eq('org1') - .where('createdAt').lt( new Date() ) + .where('createdAt').lt(new Date()) .exec() - .then(function(res){ + .then((res) => { res.length.should.eql(1); done(); }) - .catch(function(e){ + .catch((e) => { done(e); }); }) - .catch(function(e){ + .catch((e) => { done(e); }); }); }); - it('Should allow multiple local indexes and query correctly', async function () { - var schema = new dynamoose.Schema({ - id: { - type: String, - hashKey: true, + it('Should allow multiple local indexes and query correctly', async () => { + const schema = new dynamoose.Schema({ + 'id': { + 'type': String, + 'hashKey': true }, - orgId: { - type: String, - rangeKey: true, + 'orgId': { + 'type': String, + 'rangeKey': true }, - updatedAt: { - type: Date, - index: { - global: false, - name : 'OrganizationUpdatedAtIndex' + 'updatedAt': { + 'type': Date, + 'index': { + 'global': false, + 'name': 'OrganizationUpdatedAtIndex' } }, - expectedArriveAt: { - type: Date, - index: { - global: false, - name : 'OrganizationExpectedArriveAtIndex' + 'expectedArriveAt': { + 'type': Date, + 'index': { + 'global': false, + 'name': 'OrganizationExpectedArriveAtIndex' } } - },{ - throughput: 1, - timestamps: true + }, { + 'throughput': 1, + 'timestamps': true }); - var Log = dynamoose.model('Log-2', schema); + const Log = dynamoose.model('Log-2', schema); - var log1 = new Log({id: 'test1', orgId: 'org1', expectedArriveAt: Date.now()}); - var log2 = new Log({id: 'test1', orgId: 'org2', expectedArriveAt: Date.now()}); + const log1 = new Log({'id': 'test1', 'orgId': 'org1', 'expectedArriveAt': Date.now()}); + const log2 = new Log({'id': 'test1', 'orgId': 'org2', 'expectedArriveAt': Date.now()}); await log1.save(); await log2.save(); - var res = await Log.query('id').eq('test1') - .where('expectedArriveAt').lt( new Date() ) + const res = await Log.query('id').eq('test1') + .where('expectedArriveAt').lt(new Date()) .exec(); res.length.should.eql(2); - var res2 = await Log.query('id').eq('test1') - .where('updatedAt').le( log1.createdAt.getTime() ) + const res2 = await Log.query('id').eq('test1') + .where('updatedAt').le(log1.createdAt.getTime()) .exec(); res2.length.should.eql(1); }); diff --git a/test/Scan.js b/test/Scan.js index 62dc4580a..307c4b570 100644 --- a/test/Scan.js +++ b/test/Scan.js @@ -1,74 +1,74 @@ 'use strict'; -var dynamoose = require('../'); +const dynamoose = require('../'); dynamoose.AWS.config.update({ - accessKeyId: 'AKID', - secretAccessKey: 'SECRET', - region: 'us-east-1' + 'accessKeyId': 'AKID', + 'secretAccessKey': 'SECRET', + 'region': 'us-east-1' }); dynamoose.local(); -var Schema = dynamoose.Schema; +const Schema = dynamoose.Schema; -var should = require('should'); +const should = require('should'); -describe('Scan', function (){ +describe('Scan', function () { this.timeout(10000); - before(function (done) { + before((done) => { - dynamoose.setDefaults({ prefix: '', suffix: '' }); + dynamoose.setDefaults({'prefix': '', 'suffix': ''}); - var dogSchema = new Schema({ - ownerId: { - type: Number, - validate: function(v) { return v > 0; }, - hashKey: true + const dogSchema = new Schema({ + 'ownerId': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'hashKey': true }, - breed: { - type: String, - trim: true, - required: true, - index: { - global: true, - rangeKey: 'ownerId', - name: 'BreedIndex', - project: true, // ProjectionType: ALL - throughput: 5 // read and write are both 5 + 'breed': { + 'type': String, + 'trim': true, + 'required': true, + 'index': { + 'global': true, + 'rangeKey': 'ownerId', + 'name': 'BreedIndex', + 'project': true, // ProjectionType: ALL + 'throughput': 5 // read and write are both 5 } }, - name: { - type: String, - rangeKey: true, - index: true // name: nameLocalIndex, ProjectionType: ALL + 'name': { + 'type': String, + 'rangeKey': true, + 'index': true // name: nameLocalIndex, ProjectionType: ALL }, - color: { - lowercase: true, - type: [String], - default: ['Brown'] + 'color': { + 'lowercase': true, + 'type': [String], + 'default': ['Brown'] }, - cartoon: { - type: Boolean + 'cartoon': { + 'type': Boolean }, - details: { - timeWakeUp: { - type: String + 'details': { + 'timeWakeUp': { + 'type': String }, - timeSleep: { - type: String + 'timeSleep': { + 'type': String } } - }, { useDocumentTypes: true }); + }, {'useDocumentTypes': true}); function addDogs (dogs) { - if(dogs.length <= 0) { + if (dogs.length <= 0) { return done(); } - var dog = new Dog(dogs.pop()); - dog.save(function (err) { + const dog = new Dog(dogs.pop()); + dog.save((err) => { if (err) { return done(err); } @@ -79,33 +79,33 @@ describe('Scan', function (){ var Dog = dynamoose.model('Dog', dogSchema); addDogs([ - {ownerId:1, name: 'Foxy Lady', breed: 'Jack Russell Terrier ', color: ['White', 'Brown', 'Black']}, - {ownerId:2, name: 'Quincy', breed: 'Jack Russell Terrier', color: ['White', 'Brown']}, - {ownerId:2, name: 'Princes', breed: 'Jack Russell Terrier', color: ['White', 'Brown']}, - {ownerId:3, name: 'Toto', breed: 'Terrier', color: ['Brown']}, - {ownerId:4, name: 'Odie', breed: 'Beagle', color: ['Tan'], cartoon: true}, - {ownerId:5, name: 'Pluto', breed: 'unknown', color: ['Mustard'], cartoon: true}, - {ownerId:6, name: 'Brian Griffin', breed: 'unknown', color: ['White']}, - {ownerId:7, name: 'Scooby Doo', breed: 'Great Dane', cartoon: true}, - {ownerId:8, name: 'Blue', breed: 'unknown', color: ['Blue'], cartoon: true}, - {ownerId:9, name: 'Lady', breed: ' Cocker Spaniel', cartoon: true}, - {ownerId:10, name: 'Copper', breed: 'Hound', cartoon: true}, - {ownerId:11, name: 'Old Yeller', breed: 'unknown', color: ['Tan']}, - {ownerId:12, name: 'Hooch', breed: 'Dogue de Bordeaux', color: ['Brown']}, - {ownerId:13, name: 'Rin Tin Tin', breed: 'German Shepherd'}, - {ownerId:14, name: 'Benji', breed: 'unknown'}, - {ownerId:15, name: 'Wishbone', breed: 'Jack Russell Terrier', color: ['White'], details: { timeWakeUp: '6am', timeSleep: '8pm' }}, - {ownerId:16, name: 'Marley', breed: 'Labrador Retriever', color: ['Yellow']}, - {ownerId:17, name: 'Beethoven', breed: 'St. Bernard'}, - {ownerId:18, name: 'Lassie', breed: 'Collie', color: ['tan', 'white']}, - {ownerId:19, name: 'Snoopy', breed: 'Beagle', color: ['black', 'white'], cartoon: true, details: { timeWakeUp: '8am', timeSleep: '8pm' }} + {'ownerId': 1, 'name': 'Foxy Lady', 'breed': 'Jack Russell Terrier ', 'color': ['White', 'Brown', 'Black']}, + {'ownerId': 2, 'name': 'Quincy', 'breed': 'Jack Russell Terrier', 'color': ['White', 'Brown']}, + {'ownerId': 2, 'name': 'Princes', 'breed': 'Jack Russell Terrier', 'color': ['White', 'Brown']}, + {'ownerId': 3, 'name': 'Toto', 'breed': 'Terrier', 'color': ['Brown']}, + {'ownerId': 4, 'name': 'Odie', 'breed': 'Beagle', 'color': ['Tan'], 'cartoon': true}, + {'ownerId': 5, 'name': 'Pluto', 'breed': 'unknown', 'color': ['Mustard'], 'cartoon': true}, + {'ownerId': 6, 'name': 'Brian Griffin', 'breed': 'unknown', 'color': ['White']}, + {'ownerId': 7, 'name': 'Scooby Doo', 'breed': 'Great Dane', 'cartoon': true}, + {'ownerId': 8, 'name': 'Blue', 'breed': 'unknown', 'color': ['Blue'], 'cartoon': true}, + {'ownerId': 9, 'name': 'Lady', 'breed': ' Cocker Spaniel', 'cartoon': true}, + {'ownerId': 10, 'name': 'Copper', 'breed': 'Hound', 'cartoon': true}, + {'ownerId': 11, 'name': 'Old Yeller', 'breed': 'unknown', 'color': ['Tan']}, + {'ownerId': 12, 'name': 'Hooch', 'breed': 'Dogue de Bordeaux', 'color': ['Brown']}, + {'ownerId': 13, 'name': 'Rin Tin Tin', 'breed': 'German Shepherd'}, + {'ownerId': 14, 'name': 'Benji', 'breed': 'unknown'}, + {'ownerId': 15, 'name': 'Wishbone', 'breed': 'Jack Russell Terrier', 'color': ['White'], 'details': {'timeWakeUp': '6am', 'timeSleep': '8pm'}}, + {'ownerId': 16, 'name': 'Marley', 'breed': 'Labrador Retriever', 'color': ['Yellow']}, + {'ownerId': 17, 'name': 'Beethoven', 'breed': 'St. Bernard'}, + {'ownerId': 18, 'name': 'Lassie', 'breed': 'Collie', 'color': ['tan', 'white']}, + {'ownerId': 19, 'name': 'Snoopy', 'breed': 'Beagle', 'color': ['black', 'white'], 'cartoon': true, 'details': {'timeWakeUp': '8am', 'timeSleep': '8pm'}} ]); }); - after(function (done) { - var Dog = dynamoose.model('Dog'); - Dog.$__.table.delete(function (err) { - if(err) { + after((done) => { + const Dog = dynamoose.model('Dog'); + Dog.$__.table.delete((err) => { + if (err) { done(err); } delete dynamoose.models.Dog; @@ -113,260 +113,260 @@ describe('Scan', function (){ }); }); - it('Scan for all items without exec', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan for all items without exec', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({},function (err, dogs) { + Dog.scan({}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(20); done(); }); }); - it('Scan for all items', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan for all items', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan().exec(function (err, dogs) { + Dog.scan().exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(20); done(); }); }); - it('Scan on one attribute with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan on one attribute with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'breed': {eq: 'Jack Russell Terrier'}}, function (err, dogs) { + Dog.scan({'breed': {'eq': 'Jack Russell Terrier'}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); }); }); - it('Scan on one attribute', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan on one attribute', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('breed').eq('Jack Russell Terrier').exec(function (err, dogs) { + Dog.scan('breed').eq('Jack Russell Terrier').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); }); }); - it('Scan on two attribute with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan on two attribute with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'breed': {eq: 'Jack Russell Terrier'},'color':{contains:'black'}}, function (err, dogs) { + Dog.scan({'breed': {'eq': 'Jack Russell Terrier'}, 'color': {'contains': 'black'}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); done(); }); }); - it('Scan on two attribute', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan on two attribute', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('breed').eq(' Jack Russell Terrier').and().where('color').contains('black').exec(function (err, dogs) { + Dog.scan('breed').eq(' Jack Russell Terrier').and().where('color').contains('black').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); done(); }); }); - it('Scan on two attribute and a not with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan on two attribute and a not with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'breed': {eq: 'Jack Russell Terrier'},'color':{not_contains:'black'}}, function (err, dogs) { + Dog.scan({'breed': {'eq': 'Jack Russell Terrier'}, 'color': {'not_contains': 'black'}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(3); done(); }); }); - it('Scan on two attribute and a not', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan on two attribute and a not', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('breed').eq('Jack Russell Terrier').and().where('color').not().contains('black').exec(function (err, dogs) { + Dog.scan('breed').eq('Jack Russell Terrier').and().where('color').not().contains('black').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(3); done(); }); }); - it('Scan with eq with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with eq with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'breed': {eq: 'Jack Russell Terrier'}}, function (err, dogs) { + Dog.scan({'breed': {'eq': 'Jack Russell Terrier'}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); }); }); - it('Scan with eq with filter object short version', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with eq with filter object short version', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'breed': 'Jack Russell Terrier'}, function (err, dogs) { + Dog.scan({'breed': 'Jack Russell Terrier'}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); }); }); - it('Scan with eq', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with eq', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('breed').eq('Jack Russell Terrier').exec(function (err, dogs) { + Dog.scan('breed').eq('Jack Russell Terrier').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); }); }); - it('Scan with ne with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with ne with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'breed': {ne: 'Jack Russell Terrier'}}, function (err, dogs) { + Dog.scan({'breed': {'ne': 'Jack Russell Terrier'}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(16); done(); }); }); - it('Scan with not eq', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not eq', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('breed').not().eq('Jack Russell Terrier').exec(function (err, dogs) { + Dog.scan('breed').not().eq('Jack Russell Terrier').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(16); done(); }); }); - it('Scan with null with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with null with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'cartoon': {null: true}}, function (err, dogs) { + Dog.scan({'cartoon': {'null': true}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(13); done(); }); }); - it('Scan with null', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with null', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('cartoon').null().exec(function (err, dogs) { + Dog.scan('cartoon').null().exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(13); done(); }); }); - it('Scan with blank eq - same as null', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with blank eq - same as null', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('cartoon').eq('').exec(function (err, dogs) { + Dog.scan('cartoon').eq('').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(13); done(); }); }); - it('Scan with not null with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not null with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'cartoon': {null: false}}, function (err, dogs) { + Dog.scan({'cartoon': {'null': false}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(7); done(); }); }); - it('Scan with not null', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not null', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('cartoon').not().null().exec(function (err, dogs) { + Dog.scan('cartoon').not().null().exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(7); done(); }); }); - it('Scan with lt with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with lt with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'ownerId': {lt: 2}}, function (err, dogs) { + Dog.scan({'ownerId': {'lt': 2}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); done(); }); }); - it('Scan with lt', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with lt', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').lt(2).exec(function (err, dogs) { + Dog.scan('ownerId').lt(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); done(); }); }); - it('Scan with ge with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with ge with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'ownerId': {ge: 2}}, function (err, dogs) { + Dog.scan({'ownerId': {'ge': 2}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(19); done(); }); }); - it('Scan with not lt', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not lt', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').not().lt(2).exec(function (err, dogs) { + Dog.scan('ownerId').not().lt(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(19); done(); }); }); - it('Scan with gt with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with gt with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'ownerId': {gt: 2}}, function (err, dogs) { + Dog.scan({'ownerId': {'gt': 2}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(17); done(); }); }); - it('Scan with gt', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with gt', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').gt(2).exec(function (err, dogs) { + Dog.scan('ownerId').gt(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(17); done(); }); }); - it('Scan with le with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with le with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'ownerId': {le: 2}}, function (err, dogs) { + Dog.scan({'ownerId': {'le': 2}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(3); done(); }); }); - it('Scan with not gt', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not gt', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').not().gt(2).exec(function (err, dogs) { + Dog.scan('ownerId').not().gt(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(3); done(); @@ -374,10 +374,10 @@ describe('Scan', function (){ }); - it('Scan with le', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with le', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').le(2).exec(function (err, dogs) { + Dog.scan('ownerId').le(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(3); done(); @@ -385,10 +385,10 @@ describe('Scan', function (){ }); - it('Scan with not le', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not le', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').not().le(2).exec(function (err, dogs) { + Dog.scan('ownerId').not().le(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(17); done(); @@ -396,10 +396,10 @@ describe('Scan', function (){ }); - it('Scan with ge', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with ge', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').ge(2).exec(function (err, dogs) { + Dog.scan('ownerId').ge(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(19); done(); @@ -407,77 +407,77 @@ describe('Scan', function (){ }); - it('Scan with not ge', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not ge', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').not().ge(2).exec(function (err, dogs) { + Dog.scan('ownerId').not().ge(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); done(); }); }); - it('Scan with contains with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with contains with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'breed': {contains: 'Terrier'}},function (err, dogs) { + Dog.scan({'breed': {'contains': 'Terrier'}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(5); done(); }); }); - it('Scan with contains', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with contains', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('breed').contains('Terrier').exec(function (err, dogs) { + Dog.scan('breed').contains('Terrier').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(5); done(); }); }); - it('Scan with not contains with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not contains with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'breed': {not_contains: 'Terrier'}},function (err, dogs) { + Dog.scan({'breed': {'not_contains': 'Terrier'}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(15); done(); }); }); - it('Scan with not contains', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with not contains', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('breed').not().contains('Terrier').exec(function (err, dogs) { + Dog.scan('breed').not().contains('Terrier').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(15); done(); }); }); - it('Scan with beginsWith with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with beginsWith with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'name': {begins_with: 'B'}},function (err, dogs) { + Dog.scan({'name': {'begins_with': 'B'}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); }); }); - it('Scan with beginsWith', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with beginsWith', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('name').beginsWith('B').exec(function (err, dogs) { + Dog.scan('name').beginsWith('B').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); }); }); - it('Scan with not beginsWith (error)', async function () { + it('Scan with not beginsWith (error)', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -492,12 +492,12 @@ describe('Scan', function (){ error.message.should.eql('Invalid scan state: beginsWith() cannot follow not()'); }); - it('Scan with in with filter object', async function () { + it('Scan with in with filter object', async () => { const Dog = dynamoose.model('Dog'); let error, res; try { - res = await Dog.scan({'breed': {in: ['Beagle', 'Hound']}}).exec(); + res = await Dog.scan({'breed': {'in': ['Beagle', 'Hound']}}).exec(); } catch (e) { error = e; } @@ -506,7 +506,7 @@ describe('Scan', function (){ res.length.should.eql(3); }); - it('Scan with in', async function () { + it('Scan with in', async () => { const Dog = dynamoose.model('Dog'); let error, res; @@ -521,7 +521,7 @@ describe('Scan', function (){ }); - it('Scan with not in (error)', async function () { + it('Scan with not in (error)', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -536,20 +536,20 @@ describe('Scan', function (){ error.message.should.eql('Invalid scan state: in() cannot follow not()'); }); - it('Scan with between with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with between with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({'ownerId': {between: [5,8]}},function (err, dogs) { + Dog.scan({'ownerId': {'between': [5, 8]}}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); }); }); - it('Scan with between', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with between', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').between(5, 8).exec(function (err, dogs) { + Dog.scan('ownerId').between(5, 8).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(4); done(); @@ -557,7 +557,7 @@ describe('Scan', function (){ }); - it('Scan with not between (error)', async function () { + it('Scan with not between (error)', async () => { const Dog = dynamoose.model('Dog'); let error; @@ -572,7 +572,7 @@ describe('Scan', function (){ error.message.should.eql('Invalid scan state: between() cannot follow not()'); }); - it('Scan with limit', async function () { + it('Scan with limit', async () => { const Dog = dynamoose.model('Dog'); let error, res; @@ -586,19 +586,19 @@ describe('Scan', function (){ res.length.should.eql(5); }); - it('Scan with startAt key', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with startAt key', (done) => { + const Dog = dynamoose.model('Dog'); - var key = { ownerId: { N: '15' }, name: { S: 'Wishbone' } }; + const key = {'ownerId': {'N': '15'}, 'name': {'S': 'Wishbone'}}; - Dog.scan().startAt(key).exec(function (err, dogs) { + Dog.scan().startAt(key).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(15); done(); }); }); - it('Scan with limit', async function () { + it('Scan with limit', async () => { const Dog = dynamoose.model('Dog'); let error, res; @@ -615,32 +615,32 @@ describe('Scan', function (){ res[0].should.have.property('breed'); }); - it('Scan with ANDed filters (default)', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with ANDed filters (default)', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan().filter('breed').eq('unknown').filter('name').eq('Benji').exec(function (err, dogs) { + Dog.scan().filter('breed').eq('unknown').filter('name').eq('Benji').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); done(); }); }); - it('Scan with ANDed filter with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with ANDed filter with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({and:[{'breed': {eq: 'unknown'}},{'name':{eq:'Benji'}}]},function (err, dogs) { + Dog.scan({'and': [{'breed': {'eq': 'unknown'}}, {'name': {'eq': 'Benji'}}]}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(1); done(); }); }); - it('Scan with ANDed filter with filter object (error)', async function () { + it('Scan with ANDed filter with filter object (error)', async () => { const Dog = dynamoose.model('Dog'); let error; try { - await Dog.scan({and:[{'breed': {eq: 'unknown'}},{'breed':{eq:'Benji'}}]}).exec(); + await Dog.scan({'and': [{'breed': {'eq': 'unknown'}}, {'breed': {'eq': 'Benji'}}]}).exec(); } catch (e) { error = e; } @@ -650,7 +650,7 @@ describe('Scan', function (){ error.message.should.eql('Invalid scan state; %s can only be used once'); }); - it('Scan with ANDed filter', async function () { + it('Scan with ANDed filter', async () => { const Dog = dynamoose.model('Dog'); let error, res; @@ -664,86 +664,86 @@ describe('Scan', function (){ res.length.should.eql(1); }); - it('Scan with ORed filter with filter object', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with ORed filter with filter object', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan({or:[{'breed': {eq: 'unknown'}},{'name':{eq:'Odie'}}]},function (err, dogs) { + Dog.scan({'or': [{'breed': {'eq': 'unknown'}}, {'name': {'eq': 'Odie'}}]}, (err, dogs) => { should.not.exist(err); dogs.length.should.eql(6); done(); }); }); - it('Scan with ORed filters', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with ORed filters', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan().or().filter('breed').eq('unknown').filter('name').eq('Odie').exec(function (err, dogs) { + Dog.scan().or().filter('breed').eq('unknown').filter('name').eq('Odie').exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(6); done(); }); }); - it('Scan.consistent', function (done) { - var Dog = dynamoose.model('Dog'); - Dog.scan('ownerId').eq(2).consistent().exec(function (err, dogs) { + it('Scan.consistent', (done) => { + const Dog = dynamoose.model('Dog'); + Dog.scan('ownerId').eq(2).consistent().exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(2); done(); }); }); - it('Scan.all', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan.all', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan().all().limit(5).exec(function (err, dogs) { + Dog.scan().all().limit(5).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(20); done(); }); }); - it('Scan.all(1,2)', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan.all(1,2)', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan().all(1000,2).limit(5).exec(function (err, dogs) { + Dog.scan().all(1000, 2).limit(5).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(10); done(); }); }); - it('Scan using raw AWS filter', function (done) { - var Dog = dynamoose.model('Dog'); - var filter = { - FilterExpression: 'details.timeWakeUp = :wakeUp', - ExpressionAttributeValues: { + it('Scan using raw AWS filter', (done) => { + const Dog = dynamoose.model('Dog'); + const filter = { + 'FilterExpression': 'details.timeWakeUp = :wakeUp', + 'ExpressionAttributeValues': { ':wakeUp': '8am' } }; - Dog.scan(filter, { useRawAwsFilter: true }).exec() - .then(function(dogs) { + Dog.scan(filter, {'useRawAwsFilter': true}).exec() + .then((dogs) => { dogs.length.should.eql(1); done(); }) - .catch(function(err) { + .catch((err) => { should.not.exist(err); done(); }); }); - it('Scan using raw AWS filter should work with lastKey', function (done) { - var Dog = dynamoose.model('Dog'); - var filter = { - FilterExpression: 'ownerId > :ownerIdB', - ExpressionAttributeValues: { + it('Scan using raw AWS filter should work with lastKey', (done) => { + const Dog = dynamoose.model('Dog'); + const filter = { + 'FilterExpression': 'ownerId > :ownerIdB', + 'ExpressionAttributeValues': { ':ownerIdB': 1 }, - Limit: 2 + 'Limit': 2 }; - Dog.scan(filter, { useRawAwsFilter: true }).exec(function (err, dogs) { + Dog.scan(filter, {'useRawAwsFilter': true}).exec((err, dogs) => { should.not.exist(err); should.exist(dogs.lastKey); @@ -751,51 +751,51 @@ describe('Scan', function (){ }); }); - it('Scan using raw AWS filter and select count', function (done) { - var Dog = dynamoose.model('Dog'); - var filter = { - FilterExpression: 'details.timeWakeUp = :wakeUp', - ExpressionAttributeValues: { + it('Scan using raw AWS filter and select count', (done) => { + const Dog = dynamoose.model('Dog'); + const filter = { + 'FilterExpression': 'details.timeWakeUp = :wakeUp', + 'ExpressionAttributeValues': { ':wakeUp': '8am' }, - Select: 'COUNT' + 'Select': 'COUNT' }; - Dog.scan(filter, { useRawAwsFilter: true }).exec() - .then(function(counts) { + Dog.scan(filter, {'useRawAwsFilter': true}).exec() + .then((counts) => { counts.count.should.eql(1); done(); }) - .catch(function(err) { + .catch((err) => { should.not.exist(err); done(); }); }); - it('Raw AWS filter should return model instances', function (done) { - var Dog = dynamoose.model('Dog'); - var filter = { - FilterExpression: 'details.timeWakeUp = :wakeUp', - ExpressionAttributeValues: { + it('Raw AWS filter should return model instances', (done) => { + const Dog = dynamoose.model('Dog'); + const filter = { + 'FilterExpression': 'details.timeWakeUp = :wakeUp', + 'ExpressionAttributeValues': { ':wakeUp': '8am' } }; - Dog.scan(filter, { useRawAwsFilter: true }).exec() - .then(function(dogs) { + Dog.scan(filter, {'useRawAwsFilter': true}).exec() + .then((dogs) => { dogs[0].should.be.instanceof(Dog); done(); }) - .catch(function(err) { + .catch((err) => { should.not.exist(err); done(); }); }); - it('Scan parallel', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan parallel', (done) => { + const Dog = dynamoose.model('Dog'); - Dog.scan().parallel(2).exec(function (err, dogs) { + Dog.scan().parallel(2).exec((err, dogs) => { should.not.exist(err); dogs.length.should.eql(20); done(); @@ -803,11 +803,11 @@ describe('Scan', function (){ }); - it('Scan with startAt array - implied parallel', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan with startAt array - implied parallel', (done) => { + const Dog = dynamoose.model('Dog'); Dog.scan().parallel(2).limit(2).exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(4); dogs.lastKey.length.should.eql(2); dogs.count.should.eql(4); @@ -815,7 +815,7 @@ describe('Scan', function (){ dogs.timesScanned.should.eql(2); return Dog.scan().startAt(dogs.lastKey).exec(); }) - .then(function (more) { + .then((more) => { more.length.should.eql(16); more.count.should.eql(16); more.scannedCount.should.eql(16); @@ -825,11 +825,11 @@ describe('Scan', function (){ .catch(done); }); - it('Scan parallel all', function (done) { - var Dog = dynamoose.model('Dog'); + it('Scan parallel all', (done) => { + const Dog = dynamoose.model('Dog'); Dog.scan().parallel(2).limit(2).all().exec() - .then(function (dogs) { + .then((dogs) => { dogs.length.should.eql(20); should.not.exist(dogs.lastKey); done(); @@ -840,11 +840,11 @@ describe('Scan', function (){ it('Should delay when working with all and limit', function (done) { this.timeout(15000); - var startTime = Date.now(); - var Dog = dynamoose.model('Dog'); - Dog.scan().all(1000, 5).limit(1).exec(function(err, dogs) { - var endTime = Date.now(); - var timeDifference = endTime - startTime; + const startTime = Date.now(); + const Dog = dynamoose.model('Dog'); + Dog.scan().all(1000, 5).limit(1).exec((err, dogs) => { + const endTime = Date.now(); + const timeDifference = endTime - startTime; dogs.length.should.eql(5); timeDifference.should.be.above(4000); // first request executes immediately so we take the (delay * (number of rounds (or requests) - 1)) in MS. done(); @@ -856,21 +856,21 @@ describe('Scan', function (){ this.timeout(15000); const Lion = dynamoose.model('Lion1', { - id: { - type: String, - hashKey: true, - trim: true, - }, + 'id': { + 'type': String, + 'hashKey': true, + 'trim': true + } }, { - timestamps: { - createdAt: 'created_at', - updatedAt: 'updated_at', - }, + 'timestamps': { + 'createdAt': 'created_at', + 'updatedAt': 'updated_at' + } }); for (let i = 0; i < 10; i += 1) { const record = { - id: `${i}`, + 'id': `${i}` }; await new Lion(record).save(); @@ -883,14 +883,14 @@ describe('Scan', function (){ // filter by created_at const tenMinAgo = new Date().getTime() - 10 * 60 * 1000; const createdFilter = { - created_at: { gt: tenMinAgo }, + 'created_at': {'gt': tenMinAgo} }; const createdFilterRecords = await Lion.scan(createdFilter).all(0).exec(); createdFilterRecords.length.should.eql(10); // filter by updated_at const updatedFilter = { - updated_at: { gt: tenMinAgo }, + 'updated_at': {'gt': tenMinAgo} }; const updatedFilterRecords = await Lion.scan(updatedFilter).all(0).exec(); updatedFilterRecords.length.should.eql(10); diff --git a/test/Schema.js b/test/Schema.js index f74741dfa..34090f1a4 100644 --- a/test/Schema.js +++ b/test/Schema.js @@ -1,48 +1,48 @@ 'use strict'; -//var util = require('util'); +// var util = require('util'); -var dynamoose = require('../'); -var errors = require('../lib/errors'); +const dynamoose = require('../'); +const errors = require('../lib/errors'); dynamoose.AWS.config.update({ - accessKeyId: 'AKID', - secretAccessKey: 'SECRET', - region: 'us-east-1' + 'accessKeyId': 'AKID', + 'secretAccessKey': 'SECRET', + 'region': 'us-east-1' }); dynamoose.local(); -var Schema = dynamoose.Schema; +const Schema = dynamoose.Schema; -var should = require('should'); +const should = require('should'); -describe('Schema tests', function (){ +describe('Schema tests', function () { this.timeout(10000); - it('Simple schema', function (done) { - var schemaObj = { - id: Number, - name: String, - children: [Number], - aObject: Object, - aArray: Array, - aMap: { - mapId: Number, - mapName: String, - anotherMap: { - m1:String, + it('Simple schema', (done) => { + const schemaObj = { + 'id': Number, + 'name': String, + 'children': [Number], + 'aObject': Object, + 'aArray': Array, + 'aMap': { + 'mapId': Number, + 'mapName': String, + 'anotherMap': { + 'm1': String } }, - aList: [ + 'aList': [ { - listMapId: Number, - listMapName: String + 'listMapId': Number, + 'listMapName': String } ] }; - var schema = new Schema(schemaObj); + const schema = new Schema(schemaObj); schema.attributes.id.type.name.should.eql('number'); should(schema.attributes.id.isSet).not.be.ok; @@ -79,55 +79,55 @@ describe('Schema tests', function (){ done(); }); - it('Schema with basic options', function (done) { - var schema = new Schema({ - id: { - type: Number, - validate: function(v) { return v > 0; }, - rangeKey: true + it('Schema with basic options', (done) => { + const schema = new Schema({ + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'rangeKey': true }, - breed: { - type: String, - hashKey: true + 'breed': { + 'type': String, + 'hashKey': true }, - name: { - type: String, - required: true + 'name': { + 'type': String, + 'required': true }, - color: { - type: String, - default: 'Brown' + 'color': { + 'type': String, + 'default': 'Brown' }, - born: { - type: Date, - default: Date.now + 'born': { + 'type': Date, + 'default': Date.now }, - aObject: { - type: 'Object', - default: { state: 'alive' } + 'aObject': { + 'type': 'Object', + 'default': {'state': 'alive'} }, - aMap: { - type: 'map', - map: { - mapId: {type: Number, required:true }, - mapName: {type: String, required:true } + 'aMap': { + 'type': 'map', + 'map': { + 'mapId': {'type': Number, 'required': true}, + 'mapName': {'type': String, 'required': true} } }, - aList: { - type: 'list', - list: [ + 'aList': { + 'type': 'list', + 'list': [ { - listMapId: {type: Number, default: 1}, - listMapName: {type: String, default:'SomeName'} + 'listMapId': {'type': Number, 'default': 1}, + 'listMapName': {'type': String, 'default': 'SomeName'} } ] } - }, {throughput: {read: 10, write: 2}, useDocumentTypes: false, useNativeBooleans: false}); + }, {'throughput': {'read': 10, 'write': 2}, 'useDocumentTypes': false, 'useNativeBooleans': false}); schema.attributes.id.type.name.should.eql('number'); should(schema.attributes.id.isSet).not.be.ok; should.not.exist(schema.attributes.id.default); - var validator = schema.attributes.id.validator; + const validator = schema.attributes.id.validator; should.exist(validator); validator(-1).should.not.be.ok; validator(1).should.be.ok; @@ -167,86 +167,86 @@ describe('Schema tests', function (){ done(); }); - it('Schema with ttl default options', function (done) { - var schema = new Schema( + it('Schema with ttl default options', (done) => { + const schema = new Schema( { - id: Number, - name: String + 'id': Number, + 'name': String }, { - expires: 30*24*60*60 // 30 days in seconds + 'expires': 30 * 24 * 60 * 60 // 30 days in seconds } ); should.exist(schema.expires); should.exist(schema.expires.ttl); - schema.expires.ttl.should.be.equal(30*24*60*60); + schema.expires.ttl.should.be.equal(30 * 24 * 60 * 60); should.exist(schema.expires.attribute); schema.expires.attribute.should.be.equal('expires'); done(); }); - it('Schema with ttl options', function (done) { - var schema = new Schema( + it('Schema with ttl options', (done) => { + const schema = new Schema( { - id: Number, - name: String + 'id': Number, + 'name': String }, { - expires: { - ttl: 30*24*60*60, // 30 days in seconds - attribute: 'ttl' + 'expires': { + 'ttl': 30 * 24 * 60 * 60, // 30 days in seconds + 'attribute': 'ttl' } } ); should.exist(schema.expires); should.exist(schema.expires.ttl); - schema.expires.ttl.should.be.equal(30*24*60*60); + schema.expires.ttl.should.be.equal(30 * 24 * 60 * 60); should.exist(schema.expires.attribute); schema.expires.attribute.should.be.equal('ttl'); done(); }); - it('Schema with timestamps options', function (done) { - var schema1 = new Schema({ - id: { - type: Number, - validate: function(v) { return v > 0; }, - rangeKey: true - }, - name: { - type: String, - required: true + it('Schema with timestamps options', (done) => { + const schema1 = new Schema({ + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'rangeKey': true }, + 'name': { + 'type': String, + 'required': true + } }, { - throughput: {read: 10, write: 2}, - timestamps: true + 'throughput': {'read': 10, 'write': 2}, + 'timestamps': true }); - var schema2 = new Schema({ - id: { - type: Number, - validate: function(v) { return v > 0; }, - rangeKey: true - }, - name: { - type: String, - required: true + const schema2 = new Schema({ + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'rangeKey': true }, + 'name': { + 'type': String, + 'required': true + } }, { - throughput: {read: 10, write: 2}, - timestamps: { createdAt: 'createDate', updatedAt: 'lastUpdate'} + 'throughput': {'read': 10, 'write': 2}, + 'timestamps': {'createdAt': 'createDate', 'updatedAt': 'lastUpdate'} }); schema1.attributes.id.type.name.should.eql('number'); should(schema1.attributes.id.isSet).not.be.ok; should.not.exist(schema1.attributes.id.default); - var validator = schema1.attributes.id.validator; + const validator = schema1.attributes.id.validator; should.exist(validator); validator(-1).should.not.be.ok; validator(1).should.be.ok; @@ -295,21 +295,21 @@ describe('Schema tests', function (){ }); - it('Schema with timestamps options that are rangeKey', function () { - var schema = new Schema({ - id: { - type: Number, - hashKey: true + it('Schema with timestamps options that are rangeKey', () => { + const schema = new Schema({ + 'id': { + 'type': Number, + 'hashKey': true }, - started_at: { - type: Number, - rangeKey: true + 'started_at': { + 'type': Number, + 'rangeKey': true } }, { - timestamps: { - createdAt: 'started_at', - updatedAt: 'updated_at' + 'timestamps': { + 'createdAt': 'started_at', + 'updatedAt': 'updated_at' } }); @@ -331,49 +331,49 @@ describe('Schema tests', function (){ }); - it('Schema with use Document Types', function (done) { - var schema = new Schema({ - id: { - type: Number, - validate: function(v) { return v > 0; }, - rangeKey: true + it('Schema with use Document Types', (done) => { + const schema = new Schema({ + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'rangeKey': true }, - breed: { - type: String, - hashKey: true + 'breed': { + 'type': String, + 'hashKey': true }, - aObject: { - type: 'Object', - default: { state: 'alive' } + 'aObject': { + 'type': 'Object', + 'default': {'state': 'alive'} }, - anotherObject: Object, - aArray: Array, - aMap: { - mapId: Number, - mapName: String, - anotherMap:{ - m1:String, + 'anotherObject': Object, + 'aArray': Array, + 'aMap': { + 'mapId': Number, + 'mapName': String, + 'anotherMap': { + 'm1': String } }, - aList:[ + 'aList': [ { - listMapId: Number, - listMapName: String + 'listMapId': Number, + 'listMapName': String } ], - anotherMap: { - type: 'map', - map: { - mapId: {type: Number, required:true }, - mapName: {type: String, required:true } + 'anotherMap': { + 'type': 'map', + 'map': { + 'mapId': {'type': Number, 'required': true}, + 'mapName': {'type': String, 'required': true} } }, - anotherList: { - type: 'list', - list: [ + 'anotherList': { + 'type': 'list', + 'list': [ { - listMapId: {type: Number, default: 1}, - listMapName: {type: String, default:'SomeName'} + 'listMapId': {'type': Number, 'default': 1}, + 'listMapName': {'type': String, 'default': 'SomeName'} } ] } @@ -390,9 +390,9 @@ describe('Schema tests', function (){ schema.attributes.aMap.type.name.should.eql('map'); schema.attributes.aMap.attributes.mapId.type.name.should.eql('number'); schema.attributes.aMap.attributes.mapName.type.name.should.eql('string'); - should.not.exist( schema.attributes.aMap.attributes.mapId.default); - should.not.exist( schema.attributes.aMap.attributes.mapId.validator); - should( schema.attributes.aMap.attributes.mapId.required).not.be.ok; + should.not.exist(schema.attributes.aMap.attributes.mapId.default); + should.not.exist(schema.attributes.aMap.attributes.mapId.validator); + should(schema.attributes.aMap.attributes.mapId.required).not.be.ok; schema.attributes.aMap.attributes.anotherMap.attributes.m1.type.name.should.eql('string'); schema.attributes.anotherMap.attributes.mapId.type.name.should.eql('number'); @@ -412,14 +412,14 @@ describe('Schema tests', function (){ done(); }); - it('Schema with use Native Booleans', function (done) { - var schema = new Schema({ - name: String, - isAwesome: Boolean + it('Schema with use Native Booleans', (done) => { + const schema = new Schema({ + 'name': String, + 'isAwesome': Boolean }); - var Cat = dynamoose.model('Cat' + Date.now(), schema); - var fluffy = new Cat(); + const Cat = dynamoose.model(`Cat${Date.now()}`, schema); + const fluffy = new Cat(); fluffy.name = 'Fluff Johnson'; fluffy.isAwesome = true; @@ -428,52 +428,54 @@ describe('Schema tests', function (){ Cat.$__.schema.attributes.isAwesome.type.dynamo.should.eql('BOOL'); - Cat.$__.table.delete(function () { + Cat.$__.table.delete(() => { delete dynamoose.models.Cat; done(); }); }); - it('Schema with secondary indexes', function (done) { - var schema = new Schema({ - ownerId: { - type: Number, - validate: function(v) { return v > 0; }, - hashKey: true + it('Schema with secondary indexes', (done) => { + const schema = new Schema({ + 'ownerId': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'hashKey': true }, - breed: { - type: String, - rangeKey: true, - index: { - global: true, - rangeKey: 'color', - name: 'IdGlobalIndex', - project: true, // ProjectionType: ALL - throughput: 5 // read and write are both 5 + 'breed': { + 'type': String, + 'rangeKey': true, + 'index': { + 'global': true, + 'rangeKey': 'color', + 'name': 'IdGlobalIndex', + 'project': true, // ProjectionType: ALL + 'throughput': 5 // read and write are both 5 } }, - name: { - type: String, - required: true, - index: true // name: nameLocalIndex, ProjectionType: ALL + 'name': { + 'type': String, + 'required': true, + 'index': true // name: nameLocalIndex, ProjectionType: ALL }, - color: { - type: String, - default: 'Brown', - index: [{ // name: colorLocalIndex - project: ['name'] // ProjectionType: INCLUDE - },{ // name: colorGlobalIndex, no ragne key - global: true, - project: ['name', 'breed'] // ProjectionType: INCLUDE - }] + 'color': { + 'type': String, + 'default': 'Brown', + 'index': [ + { // name: colorLocalIndex + 'project': ['name'] // ProjectionType: INCLUDE + }, { // name: colorGlobalIndex, no ragne key + 'global': true, + 'project': ['name', 'breed'] // ProjectionType: INCLUDE + } + ] }, - born: { - type: Date, - default: Date.now, - index: { - name: 'birthIndex', - project: false // ProjectionType: KEYS_ONLY + 'born': { + 'type': Date, + 'default': Date.now, + 'index': { + 'name': 'birthIndex', + 'project': false // ProjectionType: KEYS_ONLY } } }); @@ -481,13 +483,13 @@ describe('Schema tests', function (){ schema.attributes.ownerId.type.name.should.eql('number'); should(schema.attributes.ownerId.isSet).not.be.ok; should.not.exist(schema.attributes.ownerId.default); - var validator = schema.attributes.ownerId.validator; + const validator = schema.attributes.ownerId.validator; should.exist(validator); validator(-1).should.not.be.ok; validator(1).should.be.ok; should(schema.attributes.ownerId.required).not.be.ok; - var breed = schema.attributes.breed; + const breed = schema.attributes.breed; breed.type.name.should.eql('string'); breed.isSet.should.not.be.ok; should.not.exist(breed.default); @@ -497,9 +499,9 @@ describe('Schema tests', function (){ breed.indexes.IdGlobalIndex.should.have.property('global', true); breed.indexes.IdGlobalIndex.should.have.property('project', true); breed.indexes.IdGlobalIndex.should.have.property('rangeKey', 'color'); - breed.indexes.IdGlobalIndex.should.have.property('throughput', {read: 5, write: 5}); + breed.indexes.IdGlobalIndex.should.have.property('throughput', {'read': 5, 'write': 5}); - var name = schema.attributes.name; + const name = schema.attributes.name; name.type.name.should.eql('string'); name.isSet.should.not.be.ok; should.not.exist(name.default); @@ -512,7 +514,7 @@ describe('Schema tests', function (){ name.indexes.nameLocalIndex.should.not.have.property('throughput'); - var color = schema.attributes.color; + const color = schema.attributes.color; color.type.name.should.eql('string'); color.isSet.should.not.be.ok; color.default().should.eql('Brown'); @@ -525,11 +527,11 @@ describe('Schema tests', function (){ color.indexes.colorLocalIndex.should.not.have.property('throughput'); color.indexes.should.have.property('colorGlobalIndex'); color.indexes.colorGlobalIndex.should.have.property('global', true); - color.indexes.colorGlobalIndex.should.have.property('project', ['name', 'breed'] ); + color.indexes.colorGlobalIndex.should.have.property('project', ['name', 'breed']); color.indexes.colorGlobalIndex.should.not.have.property('rangeKey'); - color.indexes.colorGlobalIndex.should.have.property('throughput', {read: 1, write: 1}); + color.indexes.colorGlobalIndex.should.have.property('throughput', {'read': 1, 'write': 1}); - var born = schema.attributes.born; + const born = schema.attributes.born; born.type.name.should.eql('date'); born.isSet.should.not.be.ok; born.default().should.be.ok; @@ -551,49 +553,49 @@ describe('Schema tests', function (){ done(); }); - it('Schema useDocumentTypes and useNativeBooleans should default to true', function (done) { - var schema = new Schema({ - id: { - type: Number, - validate: function(v) { return v > 0; }, - rangeKey: true + it('Schema useDocumentTypes and useNativeBooleans should default to true', (done) => { + const schema = new Schema({ + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'rangeKey': true }, - breed: { - type: String, - hashKey: true + 'breed': { + 'type': String, + 'hashKey': true }, - aObject: { - type: 'Object', - default: { state: 'alive' } + 'aObject': { + 'type': 'Object', + 'default': {'state': 'alive'} }, - anotherObject: Object, - aArray: Array, - aMap: { - mapId: Number, - mapName: String, - anotherMap:{ - m1:String, + 'anotherObject': Object, + 'aArray': Array, + 'aMap': { + 'mapId': Number, + 'mapName': String, + 'anotherMap': { + 'm1': String } }, - aList:[ + 'aList': [ { - listMapId: Number, - listMapName: String + 'listMapId': Number, + 'listMapName': String } ], - anotherMap: { - type: 'map', - map: { - mapId: {type: Number, required:true }, - mapName: {type: String, required:true } + 'anotherMap': { + 'type': 'map', + 'map': { + 'mapId': {'type': Number, 'required': true}, + 'mapName': {'type': String, 'required': true} } }, - anotherList: { - type: 'list', - list: [ + 'anotherList': { + 'type': 'list', + 'list': [ { - listMapId: {type: Number, default: 1}, - listMapName: {type: String, default:'SomeName'} + 'listMapId': {'type': Number, 'default': 1}, + 'listMapName': {'type': String, 'default': 'SomeName'} } ] } @@ -605,30 +607,30 @@ describe('Schema tests', function (){ }); - it('Schema with added instance methods', function (done) { + it('Schema with added instance methods', (done) => { - dynamoose.setDefaults({ prefix: '' }); + dynamoose.setDefaults({'prefix': ''}); - var schema = new Schema({ - id: Number + const schema = new Schema({ + 'id': Number }); - schema.method('meow', function() { + schema.method('meow', function () { this.lastcall = 'meooowwww'; }); - var Kitty = dynamoose.model('Kitty', schema); - var fizz = new Kitty(); + const Kitty = dynamoose.model('Kitty', schema); + const fizz = new Kitty(); fizz.meow(); fizz.lastcall.should.eql('meooowwww'); schema.method({ - purr:function(){this.didpurr = 1;}, - scratch:function(){this.didscratch = 1;} + 'purr' () { this.didpurr = 1; }, + 'scratch' () { this.didscratch = 1; } }); - var Tabby = dynamoose.model('Tabby', schema); - var tom = new Tabby(); + const Tabby = dynamoose.model('Tabby', schema); + const tom = new Tabby(); tom.should.not.have.property('didpurr'); tom.should.not.have.property('didscratch'); @@ -640,10 +642,10 @@ describe('Schema tests', function (){ tom.didpurr.should.be.ok; - Tabby.$__.table.delete(function () { + Tabby.$__.table.delete(() => { delete dynamoose.models.Tabby; - Kitty.$__.table.delete(function () { + Kitty.$__.table.delete(() => { delete dynamoose.models.Kitty; done(); }); @@ -651,64 +653,60 @@ describe('Schema tests', function (){ }); - it('Schema with added static methods', function (done) { + it('Schema with added static methods', (done) => { - dynamoose.setDefaults({ prefix: '' }); + dynamoose.setDefaults({'prefix': ''}); - var staticSchema = new Schema({ - name: String + const staticSchema = new Schema({ + 'name': String }); - staticSchema.static('findKittenName', function (name){ - return name + '\'s kitten'; - }); + staticSchema.static('findKittenName', (name) => `${name}'s kitten`); - var Cat = dynamoose.model('Cat' + Date.now(),staticSchema); - var kitten = Cat.findKittenName('sue'); + const Cat = dynamoose.model(`Cat${Date.now()}`, staticSchema); + const kitten = Cat.findKittenName('sue'); kitten.should.eql('sue\'s kitten'); staticSchema.static({ - findCatsByOwner:function(owner){return owner + 'fluffy';}, - findCatsByRace:function(owner){return owner + 'bobbly';} + 'findCatsByOwner' (owner) { return `${owner}fluffy`; }, + 'findCatsByRace' (owner) { return `${owner}bobbly`; } }); - var Cats = dynamoose.model('Cats',staticSchema); - var catsByOwner = Cats.findCatsByOwner('fred'); - var catsByRace = Cats.findCatsByRace('siamese'); + const Cats = dynamoose.model('Cats', staticSchema); + const catsByOwner = Cats.findCatsByOwner('fred'); + const catsByRace = Cats.findCatsByRace('siamese'); catsByOwner.should.eql('fredfluffy'); catsByRace.should.eql('siamesebobbly'); - Cat.$__.table.delete(function () { + Cat.$__.table.delete(() => { delete dynamoose.models.Cat; - Cats.$__.table.delete(function () { + Cats.$__.table.delete(() => { delete dynamoose.models.Cats; done(); }); }); }); - it('Schema with bound static methods', function (done) { + it('Schema with bound static methods', (done) => { - dynamoose.setDefaults({ prefix: '' }); + dynamoose.setDefaults({'prefix': ''}); - var staticSchema = new Schema({ - name: String + const staticSchema = new Schema({ + 'name': String }); - staticSchema.static('getKittensNamePunctuation', function (){ - return '!'; - }); + staticSchema.static('getKittensNamePunctuation', () => '!'); - staticSchema.static('findKittenName', function (name){ + staticSchema.static('findKittenName', function (name) { // Inside a static method "this" refers to the Model - return name + '\'s kitten' + this.getKittensNamePunctuation(); + return `${name}'s kitten${this.getKittensNamePunctuation()}`; }); - var Cat = dynamoose.model('Cat' + Date.now(), staticSchema); - var kittenOwners = ['Sue', 'Janice']; - var kittens = kittenOwners.map(Cat.findKittenName); + const Cat = dynamoose.model(`Cat${Date.now()}`, staticSchema); + const kittenOwners = ['Sue', 'Janice']; + const kittens = kittenOwners.map(Cat.findKittenName); kittens.should.eql(['Sue\'s kitten!', 'Janice\'s kitten!']); @@ -716,23 +714,23 @@ describe('Schema tests', function (){ }); - it('Schema with added virtual methods', function (done) { + it('Schema with added virtual methods', (done) => { - var schema = new Schema({ - name: String, - owner: String + const schema = new Schema({ + 'name': String, + 'owner': String }); schema.virtual('mergedname').get(function () { - return (this._mergedname)?this._mergedname:this.name;//this.name + this.owner; + return this._mergedname ? this._mergedname : this.name;// this.name + this.owner; }); - schema.virtual('mergedname').set(function(v){ + schema.virtual('mergedname').set(function (v) { this._mergedname = v; }); - var Cat = dynamoose.model('Cat' + Date.now(), schema); - var tim = new Cat(); + const Cat = dynamoose.model(`Cat${Date.now()}`, schema); + const tim = new Cat(); tim.name = 'tommy'; tim.owner = 'bill'; @@ -744,41 +742,41 @@ describe('Schema tests', function (){ tim.mergedname.should.eql('george'); - Cat.$__.table.delete(function () { + Cat.$__.table.delete(() => { delete dynamoose.models.Cat; done(); }); }); - it('Schema with custom parser', function (done) { + it('Schema with custom parser', (done) => { - var schema = new Schema({ - name: String, - owner: String + const schema = new Schema({ + 'name': String, + 'owner': String }, { - attributeFromDynamo: function(name, value, fallback) { + 'attributeFromDynamo' (name, value, fallback) { if (name === 'owner') { - return 'Cat Lover: ' + value.S; + return `Cat Lover: ${value.S}`; } return fallback(value); } }); - var Cat = dynamoose.model('Cat' + Date.now(), schema); - var tim = new Cat(); + const Cat = dynamoose.model(`Cat${Date.now()}`, schema); + const tim = new Cat(); tim.name = 'tommy'; tim.owner = 'bill'; - tim.save(function() { - Cat.scan().exec(function(err, models) { + tim.save(() => { + Cat.scan().exec((err, models) => { if (err) { throw err; } - var timSaved = models.pop(); + const timSaved = models.pop(); timSaved.owner.should.eql('Cat Lover: bill'); - Cat.$__.table.delete(function () { + Cat.$__.table.delete(() => { delete dynamoose.models.Cat; done(); }); @@ -786,35 +784,35 @@ describe('Schema tests', function (){ }); }); - it('Schema with custom formatter', function (done) { + it('Schema with custom formatter', (done) => { - var schema = new Schema({ - name: String, - owner: String + const schema = new Schema({ + 'name': String, + 'owner': String }, { - attributeToDynamo: function(name, value, model, fallback) { + 'attributeToDynamo' (name, value, model, fallback) { if (name === 'owner') { - return {S: 'Cat Lover: ' + value}; + return {'S': `Cat Lover: ${value}`}; } return fallback(value); } }); - var Cat = dynamoose.model('Cat' + Date.now(), schema); - var tim = new Cat(); + const Cat = dynamoose.model(`Cat${Date.now()}`, schema); + const tim = new Cat(); tim.name = 'tommy'; tim.owner = 'bill'; - tim.save(function() { - Cat.scan().exec(function(err, models) { + tim.save(() => { + Cat.scan().exec((err, models) => { if (err) { throw err; } - var timSaved = models.pop(); + const timSaved = models.pop(); timSaved.owner.should.eql('Cat Lover: bill'); - Cat.$__.table.delete(function () { + Cat.$__.table.delete(() => { delete dynamoose.models.Cat; done(); }); @@ -822,33 +820,33 @@ describe('Schema tests', function (){ }); }); - it('Attribute with custom parser', function (done) { + it('Attribute with custom parser', (done) => { - var schema = new Schema({ - name: String, - owner: { - type: String, - fromDynamo: function(json) { - return 'Cat Lover: ' + json.S; + const schema = new Schema({ + 'name': String, + 'owner': { + 'type': String, + 'fromDynamo' (json) { + return `Cat Lover: ${json.S}`; } } }); - var Cat = dynamoose.model('Cat' + Date.now(), schema); - var tim = new Cat(); + const Cat = dynamoose.model(`Cat${Date.now()}`, schema); + const tim = new Cat(); tim.name = 'tommy'; tim.owner = 'bill'; - tim.save(function() { - Cat.scan().exec(function(err, models) { + tim.save(() => { + Cat.scan().exec((err, models) => { if (err) { throw err; } - var timSaved = models.pop(); + const timSaved = models.pop(); timSaved.owner.should.eql('Cat Lover: bill'); - Cat.$__.table.delete(function () { + Cat.$__.table.delete(() => { delete dynamoose.models.Cat; done(); }); @@ -856,33 +854,33 @@ describe('Schema tests', function (){ }); }); - it('Schema with custom formatter', function (done) { + it('Schema with custom formatter', (done) => { - var schema = new Schema({ - name: String, - owner: { - type: String, - toDynamo: function(value) { - return {S: 'Cat Lover: ' + value}; + const schema = new Schema({ + 'name': String, + 'owner': { + 'type': String, + 'toDynamo' (value) { + return {'S': `Cat Lover: ${value}`}; } } }); - var Cat = dynamoose.model('Cat' + Date.now(), schema); - var tim = new Cat(); + const Cat = dynamoose.model(`Cat${Date.now()}`, schema); + const tim = new Cat(); tim.name = 'tommy'; tim.owner = 'bill'; - tim.save(function() { - Cat.scan().exec(function(err, models) { + tim.save(() => { + Cat.scan().exec((err, models) => { if (err) { throw err; } - var timSaved = models.pop(); + const timSaved = models.pop(); timSaved.owner.should.eql('Cat Lover: bill'); - Cat.$__.table.delete(function () { + Cat.$__.table.delete(() => { delete dynamoose.models.Cat; done(); }); @@ -890,137 +888,137 @@ describe('Schema tests', function (){ }); }); - it('Parses document types when saveUnknown=false and useDocumentTypes=true', async function () { + it('Parses document types when saveUnknown=false and useDocumentTypes=true', async () => { - var schema = new Schema({ - id: Number, - mapAttrib: { - aString: String, - aNumber: Number, - }, - listAttrib: { - type: 'list', - list: [String], + const schema = new Schema({ + 'id': Number, + 'mapAttrib': { + 'aString': String, + 'aNumber': Number }, + 'listAttrib': { + 'type': 'list', + 'list': [String] + } }, { - saveUnknown: false + 'saveUnknown': false }); - var model = {}; + const model = {}; await schema.parseDynamo(model, { - id: { N: '2' }, - mapAttrib: { - M: { - aString: { S: 'Fluffy' }, - aNumber: { N: '5' }, - }, - }, - listAttrib: { - L: [ - { S: 'v1' }, - { S: 'v2' }, - ], + 'id': {'N': '2'}, + 'mapAttrib': { + 'M': { + 'aString': {'S': 'Fluffy'}, + 'aNumber': {'N': '5'} + } }, + 'listAttrib': { + 'L': [ + {'S': 'v1'}, + {'S': 'v2'} + ] + } }); model.should.eql({ - id: 2, - mapAttrib: { - aString: 'Fluffy', - aNumber: 5, + 'id': 2, + 'mapAttrib': { + 'aString': 'Fluffy', + 'aNumber': 5 }, - listAttrib: [ + 'listAttrib': [ 'v1', - 'v2', - ], + 'v2' + ] }); }); - it('Parses document types when saveUnknown=true and useDocumentTypes=true', async function () { + it('Parses document types when saveUnknown=true and useDocumentTypes=true', async () => { - var schema = new Schema({ - id: Number, - anotherMap: Map, + const schema = new Schema({ + 'id': Number, + 'anotherMap': Map }, { - saveUnknown: true + 'saveUnknown': true }); - var model = {}; + const model = {}; await schema.parseDynamo(model, { - id: { N: '2' }, - mapAttrib: { - M: { - aString: { S: 'Fluffy' }, - aNumber: { N: '5' }, - }, - }, - anotherMap: { - M: { - aNestedAttribute: { S: 'I am a nested unknown sub-attribute of a known top-level attribute' }, - weHaveTheSameName: { S: 'I should be independent of the top-level field with the same name' }, + 'id': {'N': '2'}, + 'mapAttrib': { + 'M': { + 'aString': {'S': 'Fluffy'}, + 'aNumber': {'N': '5'} } }, - weHaveTheSameName: { N: 123 }, - listAttrib: { - L: [ - { S: 'v1' }, - { S: 'v2' }, - ], + 'anotherMap': { + 'M': { + 'aNestedAttribute': {'S': 'I am a nested unknown sub-attribute of a known top-level attribute'}, + 'weHaveTheSameName': {'S': 'I should be independent of the top-level field with the same name'} + } }, + 'weHaveTheSameName': {'N': 123}, + 'listAttrib': { + 'L': [ + {'S': 'v1'}, + {'S': 'v2'} + ] + } }); model.should.eql({ - id: 2, - mapAttrib: { - aString: 'Fluffy', - aNumber: 5, + 'id': 2, + 'mapAttrib': { + 'aString': 'Fluffy', + 'aNumber': 5 }, - anotherMap: { - aNestedAttribute: 'I am a nested unknown sub-attribute of a known top-level attribute', - weHaveTheSameName: 'I should be independent of the top-level field with the same name' + 'anotherMap': { + 'aNestedAttribute': 'I am a nested unknown sub-attribute of a known top-level attribute', + 'weHaveTheSameName': 'I should be independent of the top-level field with the same name' }, - weHaveTheSameName: 123, - listAttrib: [ + 'weHaveTheSameName': 123, + 'listAttrib': [ 'v1', - 'v2', - ], + 'v2' + ] }); }); - it('Parses document types to DynamoDB with nested maps within maps when saveUnknown=true and useDocumentTypes=true', async function () { + it('Parses document types to DynamoDB with nested maps within maps when saveUnknown=true and useDocumentTypes=true', async () => { - var schema = new Schema({ - id: Number, - anotherMap: Map, + const schema = new Schema({ + 'id': Number, + 'anotherMap': Map }, { - saveUnknown: true + 'saveUnknown': true }); - var model = { - id: 2, - anotherMap: { - test1: { - name: 'Bob' + const model = { + 'id': 2, + 'anotherMap': { + 'test1': { + 'name': 'Bob' }, - test2: { - name: 'Smith' + 'test2': { + 'name': 'Smith' } } }; const result = await schema.toDynamo(model); result.should.eql({ - id: { N: '2' }, - anotherMap: { - M: { - test1: { - M: { - name: { S: 'Bob' }, + 'id': {'N': '2'}, + 'anotherMap': { + 'M': { + 'test1': { + 'M': { + 'name': {'S': 'Bob'} } }, - test2: { - M: { - name: { S: 'Smith' }, + 'test2': { + 'M': { + 'name': {'S': 'Smith'} } } } @@ -1028,101 +1026,101 @@ describe('Schema tests', function (){ }); }); - it('Handle unknown attributes in DynamoDB', async function () { + it('Handle unknown attributes in DynamoDB', async () => { - var unknownSchema = new Schema({ - id: Number + const unknownSchema = new Schema({ + 'id': Number }, { - saveUnknown: true + 'saveUnknown': true }); - var model = {}; + const model = {}; await unknownSchema.parseDynamo(model, { - id: { N: 2 }, - name: { S: 'Fluffy' }, - anObject: { S: '{"a":"attribute"}' }, - numberString: { S: '1' }, - anArray: { S: '[2,{"test2": "5","test": "1"},"value1"]' }, - anObjectB: { M: {'a':{S: 'attribute'}} }, - anArrayB: { L: [{N : 1}, {N : 2}, {N : 3}]},// can't handle dissimilar items list {M: {'test2': {S: '5'},'test': {S: '1'}}},{S: "value1"}] }, - aBoolean: { S: 'true' }, - aBooleanB: { BOOL: true }, + 'id': {'N': 2}, + 'name': {'S': 'Fluffy'}, + 'anObject': {'S': '{"a":"attribute"}'}, + 'numberString': {'S': '1'}, + 'anArray': {'S': '[2,{"test2": "5","test": "1"},"value1"]'}, + 'anObjectB': {'M': {'a': {'S': 'attribute'}}}, + 'anArrayB': {'L': [{'N': 1}, {'N': 2}, {'N': 3}]}, // can't handle dissimilar items list {M: {'test2': {S: '5'},'test': {S: '1'}}},{S: "value1"}] }, + 'aBoolean': {'S': 'true'}, + 'aBooleanB': {'BOOL': true} }); model.should.eql({ - id: 2, - name: 'Fluffy', - anObject: '{"a":"attribute"}', - numberString: '1', + 'id': 2, + 'name': 'Fluffy', + 'anObject': '{"a":"attribute"}', + 'numberString': '1', // TODO: the numbers below should probably be parseInt'ed like the `numberString` attr - anArray: '[2,{"test2": "5","test": "1"},"value1"]', - anObjectB: { a: 'attribute' }, + 'anArray': '[2,{"test2": "5","test": "1"},"value1"]', + 'anObjectB': {'a': 'attribute'}, // TODO: the numbers below should probably be parseInt'ed like the `numberString` attr - anArrayB: [1, 2, 3], - aBoolean: 'true', - aBooleanB: true + 'anArrayB': [1, 2, 3], + 'aBoolean': 'true', + 'aBooleanB': true }); }); - it('Handle unknown attributes in DynamoDB when document types are set to false', async function () { + it('Handle unknown attributes in DynamoDB when document types are set to false', async () => { - var unknownSchema = new Schema({ - id: Number + const unknownSchema = new Schema({ + 'id': Number }, { - saveUnknown: true, - useDocumentTypes: false, - useNativeBooleans: false + 'saveUnknown': true, + 'useDocumentTypes': false, + 'useNativeBooleans': false }); - var model = {}; + const model = {}; try { await unknownSchema.parseDynamo(model, { - id: { N: 2 }, - name: { S: 'Fluffy' }, - anObject: { S: '{"a":"attribute"}' }, - numberString: { S: '1' }, - anArray: { S: '[2,{"test2": "5","test": "1"},"value1"]'}, - anObjectB: { M: {'a':{S: 'attribute'}} }, - anArrayB: { L: [{N:2},{M: {'test2': {S: '5'},'test': {S: '1'}}},{S: 'value1'}]}, - aBoolean: { S: 'true' }, - aBooleanB: { BOOL: true }, + 'id': {'N': 2}, + 'name': {'S': 'Fluffy'}, + 'anObject': {'S': '{"a":"attribute"}'}, + 'numberString': {'S': '1'}, + 'anArray': {'S': '[2,{"test2": "5","test": "1"},"value1"]'}, + 'anObjectB': {'M': {'a': {'S': 'attribute'}}}, + 'anArrayB': {'L': [{'N': 2}, {'M': {'test2': {'S': '5'}, 'test': {'S': '1'}}}, {'S': 'value1'}]}, + 'aBoolean': {'S': 'true'}, + 'aBooleanB': {'BOOL': true} }); - } catch(err) { + } catch (err) { // M and L aren't supported with document types are set to false err.should.be.instanceof(Error); err.should.be.instanceof(errors.ParseError); } }); - it('Throws a useful error when parsing a record that does not match the schema', async function () { + it('Throws a useful error when parsing a record that does not match the schema', async () => { const schema = new Schema({ - topLevel: { - nestedField: Boolean, + 'topLevel': { + 'nestedField': Boolean } }); - var model = {}; + const model = {}; try { await schema.parseDynamo(model, { - topLevel: { - nestedField: 'This is a string', + 'topLevel': { + 'nestedField': 'This is a string' } }); - } catch(err) { + } catch (err) { err.should.be.instanceof(errors.ParseError); err.message.should.match(/Attribute "nestedField" of type "BOOL" has an invalid value of "This is a string"/); } }); - it('Enum Should be set in schema attributes object', function (done) { - var enumData = ['Golden retriever', 'Beagle']; - var schema = new Schema({ - race: { - type: String, - enum: enumData + it('Enum Should be set in schema attributes object', (done) => { + const enumData = ['Golden retriever', 'Beagle']; + const schema = new Schema({ + 'race': { + 'type': String, + 'enum': enumData } }); @@ -1131,159 +1129,159 @@ describe('Schema tests', function (){ done(); }); - it('Enum Should throw error when using different value', function (done) { - var schema = new Schema({ - race: { - type: String, - enum: ['Golden retriever', 'Beagle'] + it('Enum Should throw error when using different value', (done) => { + const schema = new Schema({ + 'race': { + 'type': String, + 'enum': ['Golden retriever', 'Beagle'] } }); - var Dog = dynamoose.model('Dog' + Date.now(), schema); - var oscar = new Dog(); + const Dog = dynamoose.model(`Dog${Date.now()}`, schema); + const oscar = new Dog(); oscar.race = 'Persian'; - oscar.save(function(err) { + oscar.save((err) => { err.should.be.instanceof(Error); err.should.be.instanceof(errors.ValidationError); done(); }); }); - it('Enum Should not throw an error if value is empty', function (done) { - var schema = new Schema({ - name: { - type: String, - required: true, - hashKey: true + it('Enum Should not throw an error if value is empty', (done) => { + const schema = new Schema({ + 'name': { + 'type': String, + 'required': true, + 'hashKey': true }, - race: { - type: String, - enum: ['Golden retriever', 'Beagle'] + 'race': { + 'type': String, + 'enum': ['Golden retriever', 'Beagle'] }, - weight: { - type: Number + 'weight': { + 'type': Number } }); - var Dog = dynamoose.model('Dog' + Date.now(), schema); - var oscar = new Dog(); + const Dog = dynamoose.model(`Dog${Date.now()}`, schema); + const oscar = new Dog(); oscar.name = 'oscar'; oscar.weight = 100; - oscar.save(function(err) { + oscar.save((err) => { should(err).be.null(); - Dog.$__.table.delete(function () { + Dog.$__.table.delete(() => { delete dynamoose.models.Dog; done(); }); }); }); - it('Enum Should save new instance of model with a good value', function (done) { + it('Enum Should save new instance of model with a good value', (done) => { - var enumData = ['Golden retriever', 'Beagle']; - var choosedRace = enumData[0]; + const enumData = ['Golden retriever', 'Beagle']; + const choosedRace = enumData[0]; - var schema = new Schema({ - race: { - type: String, - enum: enumData + const schema = new Schema({ + 'race': { + 'type': String, + 'enum': enumData } }); - var Dog = dynamoose.model('Dog' + Date.now(), schema); - var oscar = new Dog(); + const Dog = dynamoose.model(`Dog${Date.now()}`, schema); + const oscar = new Dog(); oscar.race = choosedRace; - oscar.save(function(err, savedDog) { + oscar.save((err, savedDog) => { should(err).be.null(); savedDog.race.should.equal(choosedRace); - Dog.$__.table.delete(function () { + Dog.$__.table.delete(() => { delete dynamoose.models.Dog; done(); }); }); }); - it('Handle unknown attributes as array in DynamoDB', async function () { + it('Handle unknown attributes as array in DynamoDB', async () => { - var unknownSchema = new Schema({ - id: Number + const unknownSchema = new Schema({ + 'id': Number }, { - saveUnknown: ['name', 'numberString'] + 'saveUnknown': ['name', 'numberString'] }); - var model = {}; + const model = {}; await unknownSchema.parseDynamo(model, { - id: { N: '2' }, - name: { S: 'Fluffy' }, - anObject: { S: '{"a":"attribute"}' }, - numberString: { S: '1' } + 'id': {'N': '2'}, + 'name': {'S': 'Fluffy'}, + 'anObject': {'S': '{"a":"attribute"}'}, + 'numberString': {'S': '1'} }); model.should.eql({ - id: 2, - name: 'Fluffy', - numberString: '1' + 'id': 2, + 'name': 'Fluffy', + 'numberString': '1' }); }); - it('Handle unknown attributes as array in DynamoDB when document types are set to false', async function () { + it('Handle unknown attributes as array in DynamoDB when document types are set to false', async () => { - var unknownSchema = new Schema({ - id: Number + const unknownSchema = new Schema({ + 'id': Number }, { - saveUnknown: ['name', 'numberString'], - useDocumentTypes: false, - useNativeBooleans: false + 'saveUnknown': ['name', 'numberString'], + 'useDocumentTypes': false, + 'useNativeBooleans': false }); - var model = {}; + const model = {}; await unknownSchema.parseDynamo(model, { - id: { N: '2' }, - name: { S: 'Fluffy' }, - anObject: { S: '{"a":"attribute"}' }, - numberString: { S: '1' } + 'id': {'N': '2'}, + 'name': {'S': 'Fluffy'}, + 'anObject': {'S': '{"a":"attribute"}'}, + 'numberString': {'S': '1'} }); model.should.eql({ - id: 2, - name: 'Fluffy', - numberString: '1' + 'id': 2, + 'name': 'Fluffy', + 'numberString': '1' }); }); - it('Errors when encountering an unknown attribute if errorUnknown is set to true', async function () { + it('Errors when encountering an unknown attribute if errorUnknown is set to true', async () => { const schema = new Schema({ - myHashKey: { - hashKey: true, - type: String, + 'myHashKey': { + 'hashKey': true, + 'type': String }, - myRangeKey: { - rangeKey: true, - type: String, + 'myRangeKey': { + 'rangeKey': true, + 'type': String }, - knownAttribute: String, + 'knownAttribute': String }, { - errorUnknown: true, + 'errorUnknown': true }); let err; - const model = {['$__']: { - name: 'OnlyKnownAttributesModel' + const model = {'$__': { + 'name': 'OnlyKnownAttributesModel' }}; try { await schema.parseDynamo(model, { - myHashKey: 'I am the hash key', - myRangeKey: 'I am the range key', - knownAttribute: { S: 'I am known to the schema. Everything is groovy.' }, - unknownAttribute: { S: 'I am but a stranger to the schema. I should cause an error.' } + 'myHashKey': 'I am the hash key', + 'myRangeKey': 'I am the range key', + 'knownAttribute': {'S': 'I am known to the schema. Everything is groovy.'}, + 'unknownAttribute': {'S': 'I am but a stranger to the schema. I should cause an error.'} }); } catch (e) { err = e; @@ -1294,35 +1292,35 @@ describe('Schema tests', function (){ }); - it('Errors when encountering an unknown nested attribute if errorUnknown is set to true', async function () { + it('Errors when encountering an unknown nested attribute if errorUnknown is set to true', async () => { const schema = new Schema({ - myHashKey: { - hashKey: true, - type: String, + 'myHashKey': { + 'hashKey': true, + 'type': String }, - myRangeKey: { - rangeKey: true, - type: String, + 'myRangeKey': { + 'rangeKey': true, + 'type': String }, - knownAttribute: String, - myMap: Map, + 'knownAttribute': String, + 'myMap': Map }, { - errorUnknown: true, + 'errorUnknown': true }); let err; - const model = {['$__']: { - name: 'OnlyKnownAttributesModel' + const model = {'$__': { + 'name': 'OnlyKnownAttributesModel' }}; try { await schema.parseDynamo(model, { - myHashKey: 'I am the hash key', - myRangeKey: 'I am the range key', - knownAttribute: { S: 'I am known to the schema. Everything is groovy.' }, - myMap: { - M: { - nestedUnknownAttribute: { S: 'I too am a stranger. Will the schema be able to find me down here?' } + 'myHashKey': 'I am the hash key', + 'myRangeKey': 'I am the range key', + 'knownAttribute': {'S': 'I am known to the schema. Everything is groovy.'}, + 'myMap': { + 'M': { + 'nestedUnknownAttribute': {'S': 'I too am a stranger. Will the schema be able to find me down here?'} } } }); @@ -1334,12 +1332,12 @@ describe('Schema tests', function (){ err.message.should.match(/Unknown nested attribute nestedUnknownAttribute with value: {"S":"I too am a stranger. Will the schema be able to find me down here\?"}/); }); - it('Should throw error when type is map but no map is provided', function (done) { + it('Should throw error when type is map but no map is provided', (done) => { let err; try { new Schema({ - race: { - type: 'map', + 'race': { + 'type': 'map' } }); } catch (e) { @@ -1351,12 +1349,12 @@ describe('Schema tests', function (){ done(); }); - it('Should throw error when type is list but no list is provided', function (done) { + it('Should throw error when type is list but no list is provided', (done) => { let err; try { new Schema({ - race: { - type: 'list', + 'race': { + 'type': 'list' } }); } catch (e) { @@ -1368,9 +1366,9 @@ describe('Schema tests', function (){ err = undefined; try { new Schema({ - race: { - type: 'list', - list: [] + 'race': { + 'type': 'list', + 'list': [] } }); } catch (e) { diff --git a/test/Table.js b/test/Table.js index e2cd2140d..f5286b954 100755 --- a/test/Table.js +++ b/test/Table.js @@ -1,94 +1,94 @@ 'use strict'; -var dynamoose = require('../'); +const dynamoose = require('../'); dynamoose.AWS.config.update({ - accessKeyId: 'AKID', - secretAccessKey: 'SECRET', - region: 'us-east-1' + 'accessKeyId': 'AKID', + 'secretAccessKey': 'SECRET', + 'region': 'us-east-1' }); dynamoose.local(); -var Schema = dynamoose.Schema; -var Table = dynamoose.Table; +const Schema = dynamoose.Schema; +const Table = dynamoose.Table; -var should = require('should'); +const should = require('should'); describe('Table tests', function () { this.timeout(10000); - var schema = new Schema({id: Number, name: String, childern: [Number], address: {street: String, city: String}}); - var globalIndexSchema = new Schema({ - ownerId: { - type: Number, - validate: function (v) { + const schema = new Schema({'id': Number, 'name': String, 'childern': [Number], 'address': {'street': String, 'city': String}}); + const globalIndexSchema = new Schema({ + 'ownerId': { + 'type': Number, + 'validate' (v) { return v > 0; }, - hashKey: true + 'hashKey': true }, - breed: { - type: String, - rangeKey: true, - index: { - global: true, - rangeKey: 'color', - name: 'BreedGlobalIndex', - project: true, // ProjectionType: ALL - throughput: 5 // read and write are both 5 + 'breed': { + 'type': String, + 'rangeKey': true, + 'index': { + 'global': true, + 'rangeKey': 'color', + 'name': 'BreedGlobalIndex', + 'project': true, // ProjectionType: ALL + 'throughput': 5 // read and write are both 5 } }, - name: { - type: String, - required: true, - index: { - global: true, - name: 'NameGlobalIndex', - project: true, // ProjectionType: ALL - throughput: 5 // read and write are both 5 + 'name': { + 'type': String, + 'required': true, + 'index': { + 'global': true, + 'name': 'NameGlobalIndex', + 'project': true, // ProjectionType: ALL + 'throughput': 5 // read and write are both 5 } }, - color: { - type: String, - default: 'Brown' + 'color': { + 'type': String, + 'default': 'Brown' } }); - var table = new Table('person', schema, null, dynamoose); - var globalIndexTable = new Table('dog', globalIndexSchema, null, dynamoose); + const table = new Table('person', schema, null, dynamoose); + const globalIndexTable = new Table('dog', globalIndexSchema, null, dynamoose); - it('Create simple table', function (done) { + it('Create simple table', (done) => { - table.create(function (err) { + table.create((err) => { should.not.exist(err); done(); }); }); - it('Describe simple table', function (done) { + it('Describe simple table', (done) => { - table.describe(function (err, data) { + table.describe((err, data) => { should.not.exist(err); should.exist(data); done(); }); }); - it('Delete simple table', function (done) { + it('Delete simple table', (done) => { - table.delete(function (err, data) { + table.delete((err, data) => { should.not.exist(err); should.exist(data); done(); }); }); - it('Describe missing table', function (done) { - var missing = new Table('missing', schema, null, dynamoose); + it('Describe missing table', (done) => { + const missing = new Table('missing', schema, null, dynamoose); - missing.describe(function (err, data) { + missing.describe((err, data) => { should.exist(err); should.not.exist(data); err.code.should.eql('ResourceNotFoundException'); @@ -96,79 +96,78 @@ describe('Table tests', function () { }); }); - it('Create table with global index with non indexed range key', function (done) { + it('Create table with global index with non indexed range key', (done) => { - globalIndexTable.create(function (err) { + globalIndexTable.create((err) => { should.not.exist(err); done(); }); }); - it('Delete table with global index', function (done) { + it('Delete table with global index', (done) => { - globalIndexTable.delete(function (err, data) { + globalIndexTable.delete((err, data) => { should.not.exist(err); should.exist(data); done(); }); }); - it('create DMSong with limited projection', function (done) { - var Song = dynamoose.model('DMSong', { - id: { - type: Number, - required: true, - hashKey: true, + it('create DMSong with limited projection', (done) => { + const Song = dynamoose.model('DMSong', { + 'id': { + 'type': Number, + 'required': true, + 'hashKey': true }, - band: { - type: String, - required: true, - trim: true + 'band': { + 'type': String, + 'required': true, + 'trim': true }, - album: { - type: String, - required: true, - trim: true, - index: { - global: true, - rangeKey: 'id', - name: 'albumIndex', - project: ['band', 'album'], - throughput: 5 // read and write are both 5 + 'album': { + 'type': String, + 'required': true, + 'trim': true, + 'index': { + 'global': true, + 'rangeKey': 'id', + 'name': 'albumIndex', + 'project': ['band', 'album'], + 'throughput': 5 // read and write are both 5 } }, - song: { - type: String, - required: true, - trim: true, - index: { - global: true, - rangeKey: 'id', - name: 'songIndex', - project: true, // ProjectionType: ALL - throughput: 5 // read and write are both 5 + 'song': { + 'type': String, + 'required': true, + 'trim': true, + 'index': { + 'global': true, + 'rangeKey': 'id', + 'name': 'songIndex', + 'project': true, // ProjectionType: ALL + 'throughput': 5 // read and write are both 5 } }, - track: { - type: Number, - required: false, + 'track': { + 'type': Number, + 'required': false } }, { - create: true, update: true + 'create': true, 'update': true }); - var tom_sawyer = new Song({id: 1, band: 'Rush', album: 'Moving Pictures', song: 'Tom Sawyer', track: 1}); + const tom_sawyer = new Song({'id': 1, 'band': 'Rush', 'album': 'Moving Pictures', 'song': 'Tom Sawyer', 'track': 1}); tom_sawyer.save(); - var params = {TableName: 'DMSong'}; - setTimeout(function() { - dynamoose.ddb().describeTable(params, function (err, data) { + const params = {'TableName': 'DMSong'}; + setTimeout(() => { + dynamoose.ddb().describeTable(params, (err, data) => { if (err) { done(err); - } - else { - var found = false; - for (var i in data.Table.GlobalSecondaryIndexes) { - var gsi = data.Table.GlobalSecondaryIndexes[i]; + } else { + let found = false; + for (const i in data.Table.GlobalSecondaryIndexes) { + const gsi = data.Table.GlobalSecondaryIndexes[i]; if (gsi.IndexName === 'albumIndex') { should.equal(gsi.Projection.ProjectionType, 'INCLUDE'); found = true; @@ -181,68 +180,67 @@ describe('Table tests', function () { }); }, 2000); }); - it('update DMSong with broader projection', function (done) { - var Song = dynamoose.model('DMSong', { - id: { - type: Number, - required: true, - hashKey: true, + it('update DMSong with broader projection', (done) => { + const Song = dynamoose.model('DMSong', { + 'id': { + 'type': Number, + 'required': true, + 'hashKey': true }, - band: { - type: String, - required: true, - trim: true + 'band': { + 'type': String, + 'required': true, + 'trim': true }, - album: { - type: String, - required: true, - trim: true, - index: { - global: true, - rangeKey: 'id', - name: 'albumIndex', - project: true, // ProjectionType: ALL - throughput: 5 // read and write are both 5 + 'album': { + 'type': String, + 'required': true, + 'trim': true, + 'index': { + 'global': true, + 'rangeKey': 'id', + 'name': 'albumIndex', + 'project': true, // ProjectionType: ALL + 'throughput': 5 // read and write are both 5 } }, - song: { - type: String, - required: true, - trim: true, - index: { - global: true, - rangeKey: 'id', - name: 'songIndex', - project: true, // ProjectionType: ALL - throughput: 5 // read and write are both 5 + 'song': { + 'type': String, + 'required': true, + 'trim': true, + 'index': { + 'global': true, + 'rangeKey': 'id', + 'name': 'songIndex', + 'project': true, // ProjectionType: ALL + 'throughput': 5 // read and write are both 5 } }, - track: { - type: Number, - required: false, + 'track': { + 'type': Number, + 'required': false } }, { - create: true, - update: true, - waitForActive: true + 'create': true, + 'update': true, + 'waitForActive': true }); - var red_barchetta = new Song({id: 2, band: 'Rush', album: 'Moving Pictures', song: 'Red Barchetta', track: 2}); + const red_barchetta = new Song({'id': 2, 'band': 'Rush', 'album': 'Moving Pictures', 'song': 'Red Barchetta', 'track': 2}); red_barchetta.save(); - var params = {TableName: 'DMSong'}; - setTimeout(function() { - dynamoose.ddb().describeTable(params, function (err, data) { + const params = {'TableName': 'DMSong'}; + setTimeout(() => { + dynamoose.ddb().describeTable(params, (err, data) => { if (err) { done(err); - } - else { + } else { // console.log("---------------------REVISED TABLE"); // console.log(JSON.stringify(data, null, 2)); - var found = false; - for (var i in data.Table.GlobalSecondaryIndexes) { - var gsi = data.Table.GlobalSecondaryIndexes[i]; + let found = false; + for (const i in data.Table.GlobalSecondaryIndexes) { + const gsi = data.Table.GlobalSecondaryIndexes[i]; if (gsi.IndexName === 'albumIndex') { should.equal(gsi.Projection.ProjectionType, 'ALL'); found = true; diff --git a/test/fixtures/Cats.js b/test/fixtures/Cats.js index d69c7d773..581742810 100644 --- a/test/fixtures/Cats.js +++ b/test/fixtures/Cats.js @@ -1,371 +1,377 @@ 'use strict'; -module.exports = function(dynamoose){ - const ONE_YEAR = 365*24*60*60; // 1 years in seconds - const NINE_YEARS = 9*ONE_YEAR; // 9 years in seconds +module.exports = function (dynamoose) { + const ONE_YEAR = 365 * 24 * 60 * 60; // 1 years in seconds + const NINE_YEARS = 9 * ONE_YEAR; // 9 years in seconds const Cat = dynamoose.model('Cat', { - id: { - type: Number, - validate: function (v) { return v > 0; } - }, - name: String, - owner: String, - age: { type: Number }, - vet:{ - name: String, - address: String - }, - ears:[{ - name: String - }], - legs: [String], - profileImage: Buffer, - more: Object, - array: Array, - validated: { - type: String, - validate: function (v) { return v === 'valid'; } + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; } + }, + 'name': String, + 'owner': String, + 'age': {'type': Number}, + 'vet': { + 'name': String, + 'address': String + }, + 'ears': [ + { + 'name': String + } + ], + 'legs': [String], + 'profileImage': Buffer, + 'more': Object, + 'array': Array, + 'validated': { + 'type': String, + 'validate' (v) { return v === 'valid'; } } }); // Create a model with unnamed attributes const Cat1 = dynamoose.model('Cat1', { - id: { - type: Number, - validate: function (v) { return v > 0; }, - default: 888 - }, - name: { - type: String, - required: true, - default: 'Mittens' - }, - owner: String - }, {saveUnknown: true}); + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'default': 888 + }, + 'name': { + 'type': String, + 'required': true, + 'default': 'Mittens' + }, + 'owner': String + }, {'saveUnknown': true}); // Create a model with a range key const Cat2 = dynamoose.model('Cat2', { - ownerId: { - type: Number, - hashKey: true + 'ownerId': { + 'type': Number, + 'hashKey': true }, - name: { - type: String, - rangeKey: true + 'name': { + 'type': String, + 'rangeKey': true } }); // Create a model with required attributes const Cat3 = dynamoose.model('Cat3', { - id: { - type: Number, - validate: function (v) { return v > 0; }, - default: 888 - }, - name: { - type: String, - required: true, - default: 'Mittens' - }, - owner: String, - age: { - type: Number, - required: true + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'default': 888 + }, + 'name': { + 'type': String, + 'required': true, + 'default': 'Mittens' + }, + 'owner': String, + 'age': { + 'type': Number, + 'required': true } }); // Create a model with timestamps const Cat4 = dynamoose.model('Cat4', { - id: { - type: Number, - validate: function (v) { return v > 0; } + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; } }, - name: { - type: String, - default: 'Bobo' + 'name': { + 'type': String, + 'default': 'Bobo' } }, { - timestamps: { - createdAt: 'myLittleCreatedAt', - updatedAt: 'myLittleUpdatedAt' + 'timestamps': { + 'createdAt': 'myLittleCreatedAt', + 'updatedAt': 'myLittleUpdatedAt' } }); // Create a model with unnamed attributes const Cat5 = dynamoose.model('Cat5', { - id: { - type: Number, - validate: function (v) { return v > 0; }, - default: 888 + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; }, + 'default': 888 }, - name: { - type: String, - required: true, - default: 'Mittens' + 'name': { + 'type': String, + 'required': true, + 'default': 'Mittens' }, - owner: String, + 'owner': String }, { - saveUnknown: true + 'saveUnknown': true }); const Cat6 = dynamoose.model('Cat6', { - id: { - type: Number + 'id': { + 'type': Number }, - name: { - type: String + 'name': { + 'type': String }, - parent: { - type: Number, - ref: 'Cat6' + 'parent': { + 'type': Number, + 'ref': 'Cat6' } }); const Cat7 = dynamoose.model('Cat7', { - id: { - type: Number, - hashKey: true + 'id': { + 'type': Number, + 'hashKey': true }, - name: { - type: String + 'name': { + 'type': String }, - parent: Number, - isHappy: Boolean - }, {useDocumentTypes: false, useNativeBooleans: false}); + 'parent': Number, + 'isHappy': Boolean + }, {'useDocumentTypes': false, 'useNativeBooleans': false}); const Cat8 = dynamoose.model('Cat8', { - id: { - type: Number, - hashKey: true + 'id': { + 'type': Number, + 'hashKey': true }, - age: { - type: Number, - rangeKey: true + 'age': { + 'type': Number, + 'rangeKey': true } }); const CatWithOwner = dynamoose.model('CatWithOwner', { - id: { - type: Number + 'id': { + 'type': Number }, - name: { - type: String + 'name': { + 'type': String }, - owner: { - name: String, - address: String + 'owner': { + 'name': String, + 'address': String } }); const Owner = dynamoose.model('Owner', { - name: { - type: String, - hashKey: true + 'name': { + 'type': String, + 'hashKey': true }, - address: { - type: String, - rangeKey: true + 'address': { + 'type': String, + 'rangeKey': true }, - phoneNumber: String + 'phoneNumber': String }); const ExpiringCat = dynamoose.model('ExpiringCat', { - name: String - }, {expires: NINE_YEARS}); + 'name': String + }, {'expires': NINE_YEARS}); const ExpiringCatNull = dynamoose.model('ExpiringCatNull', { - name: String + 'name': String }, { - expires: { - ttl: NINE_YEARS, - attribute: 'expires', - defaultExpires: function() { + 'expires': { + 'ttl': NINE_YEARS, + 'attribute': 'expires', + 'defaultExpires' () { return null; } } }); const ExpiringCatNoReturn = dynamoose.model('ExpiringCatNoReturn', { - name: String + 'name': String }, { - expires: { - ttl: NINE_YEARS, - attribute: 'expires', - returnExpiredItems: false, - defaultExpires: function() { + 'expires': { + 'ttl': NINE_YEARS, + 'attribute': 'expires', + 'returnExpiredItems': false, + 'defaultExpires' () { return null; } } }); const ExpiringCatReturnTrue = dynamoose.model('ExpiringCatReturnTrue', { - name: String + 'name': String }, { - expires: { - ttl: NINE_YEARS, - attribute: 'expires', - returnExpiredItems: true, - defaultExpires: function() { + 'expires': { + 'ttl': NINE_YEARS, + 'attribute': 'expires', + 'returnExpiredItems': true, + 'defaultExpires' () { return null; } } }); const CatWithGeneratedID = dynamoose.model('CatWithGeneratedID', { - id: { - type: String, - default: function (model) { - return model.owner.name + '_' + model.name; + 'id': { + 'type': String, + 'default' (model) { + return `${model.owner.name}_${model.name}`; }, - validate: function (value, model) { - return value === model.owner.name + '_' + model.name; + 'validate' (value, model) { + return value === `${model.owner.name}_${model.name}`; } }, - name: { - type: String, + 'name': { + 'type': String }, - owner: { - name: String, - address: String + 'owner': { + 'name': String, + 'address': String } }); const CatModel = dynamoose.model('CatDefault', { - id: { - type: Number, - validate: function (v) { return v > 0; } - }, - name: String, - owner: String, - shouldRemainUnchanged: { - type: String, - default: function(model) { - return 'shouldRemainUnchanged_'+ model.name +'_'+ model.owner; + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; } + }, + 'name': String, + 'owner': String, + 'shouldRemainUnchanged': { + 'type': String, + 'default' (model) { + return `shouldRemainUnchanged_${model.name}_${model.owner}`; } }, - shouldBeChanged: { - type: String, - default: function(model) { - return 'shouldBeChanged_'+ model.name +'_'+ model.owner; + 'shouldBeChanged': { + 'type': String, + 'default' (model) { + return `shouldBeChanged_${model.name}_${model.owner}`; } }, - shouldAlwaysBeChanged: { - type: String, - default: function(model) { - return 'shouldAlwaysBeChanged_'+ model.name +'_'+ model.owner; + 'shouldAlwaysBeChanged': { + 'type': String, + 'default' (model) { + return `shouldAlwaysBeChanged_${model.name}_${model.owner}`; }, - forceDefault: true + 'forceDefault': true }, - unsetShouldBeChanged: { - type: String, - default: function(model) { - return 'unsetShouldBeChanged_'+ model.name +'_'+ model.owner; + 'unsetShouldBeChanged': { + 'type': String, + 'default' (model) { + return `unsetShouldBeChanged_${model.name}_${model.owner}`; } }, - unsetShouldAlwaysBeChanged: { - type: String, - default: function(model) { - return 'unsetShouldAlwaysBeChanged_'+ model.name +'_'+ model.owner; + 'unsetShouldAlwaysBeChanged': { + 'type': String, + 'default' (model) { + return `unsetShouldAlwaysBeChanged_${model.name}_${model.owner}`; } } }); const Cat9 = dynamoose.model('Cat9', { - id: { - type: Number, - validate: function (v) { return v > 0; } - }, - name: String, - owner: String, - age: { type: Number }, - vet:{ - name: String, - address: String - }, - ears:[{ - name: String - }], - legs: [String], - more: Object, - array: Array, - validated: { - type: String, - validate: function (v) { return v === 'valid'; } + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; } + }, + 'name': String, + 'owner': String, + 'age': {'type': Number}, + 'vet': { + 'name': String, + 'address': String + }, + 'ears': [ + { + 'name': String + } + ], + 'legs': [String], + 'more': Object, + 'array': Array, + 'validated': { + 'type': String, + 'validate' (v) { return v === 'valid'; } } - }, {timestamps: true}); + }, {'timestamps': true}); const Cat10 = dynamoose.model('Cat10', { - id: { - type: Number, - hashKey: true - }, - isHappy: Boolean, - parents: Array, - details: Object - }, {useDocumentTypes: false, useNativeBooleans: false}); + 'id': { + 'type': Number, + 'hashKey': true + }, + 'isHappy': Boolean, + 'parents': Array, + 'details': Object + }, {'useDocumentTypes': false, 'useNativeBooleans': false}); const Cat11 = dynamoose.model('Cat11', { - id: { - type: Number, - validate: function(v) { + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; } }, - name: String, - owner: String, - age: { - type: Number - }, - vet: { - name: String, - address: String - }, - ears: [{ - name: String - }], - legs: [String], - more: Object, - array: Array, - validated: { - type: String, - validate: function(v) { + 'name': String, + 'owner': String, + 'age': { + 'type': Number + }, + 'vet': { + 'name': String, + 'address': String + }, + 'ears': [ + { + 'name': String + } + ], + 'legs': [String], + 'more': Object, + 'array': Array, + 'validated': { + 'type': String, + 'validate' (v) { return v === 'valid'; } } }, { - useDocumentTypes: true, - expires: NINE_YEARS + 'useDocumentTypes': true, + 'expires': NINE_YEARS }); const Cat12 = dynamoose.model('Cat12', { - _id: { - type: Number, - validate: function (v) { return v > 0; } + '_id': { + 'type': Number, + 'validate' (v) { return v > 0; } }, - name: String + 'name': String }); const Cat13 = dynamoose.model('Cat13', { - id: { - type: Number, - validate: function (v) { return v > 0; } + 'id': { + 'type': Number, + 'validate' (v) { return v > 0; } }, - items: { - type: 'list', - list: [ + 'items': { + 'type': 'list', + 'list': [ { - name: { - type: String, - required: true + 'name': { + 'type': String, + 'required': true }, - amount: { - type: Number, - required: true + 'amount': { + 'type': Number, + 'required': true } } ] @@ -373,8 +379,8 @@ module.exports = function(dynamoose){ }); const CatWithMethodsSchema = new dynamoose.Schema({ - id: Number, - name: String + 'id': Number, + 'name': String }); CatWithMethodsSchema.method('getModel', function (modelName) { return this.model(modelName); @@ -382,10 +388,10 @@ module.exports = function(dynamoose){ const CatWithMethods = dynamoose.model('CatWithMethods', CatWithMethodsSchema); const ReturnValuesNoneCat = dynamoose.model('ReturnValuesNoneCat', { - id: Number, - name: String, - },{ - defaultReturnValues: 'NONE', + 'id': Number, + 'name': String + }, { + 'defaultReturnValues': 'NONE' }); return {