diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..f6b9638a --- /dev/null +++ b/.eslintignore @@ -0,0 +1,3 @@ +node_modules/ +coverage/ +tmp/ \ No newline at end of file diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000..ff93f650 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,45 @@ +{ + "extends": "eslint:recommended", + "root": true, + "rules": { + "curly": [2, "multi-line"], + "no-console": 0, + "no-path-concat": 2, + "handle-callback-err": 2, + "no-use-before-define": [2, "nofunc"], + "no-shadow-restricted-names": 2, + "block-scoped-var": 2, + "dot-notation": 2, + "eqeqeq": [2, "allow-null"], + "no-else-return": 1, + "no-extend-native": 2, + "no-extra-bind": 2, + "no-implied-eval": 2, + "no-lone-blocks": 2, + "no-loop-func": 2, + "no-multi-spaces": 2, + "no-multi-str": 2, + "no-native-reassign": 2, + "no-new-wrappers": 2, + "no-redeclare": 2, + "no-return-assign": 2, + "no-throw-literal": 2, + "no-unused-expressions": [2, { + "allowShortCircuit": true, + "allowTernary": true + }], + "no-useless-call": 2, + "no-useless-concat": 2, + "no-with": 2, + "radix": 2, + "no-self-compare": 2, + "no-unused-vars": [2, { + "vars": "all", + "args": "none" + }], + "strict": [2, "global"] + }, + "env": { + "node": true + } +} \ No newline at end of file diff --git a/.jscsrc b/.jscsrc new file mode 100644 index 00000000..e9b94ed1 --- /dev/null +++ b/.jscsrc @@ -0,0 +1,85 @@ +{ + "excludeFiles": ["node_modules/**", "coverage/**", "tmp/**"], + "validateIndentation": 2, + "validateLineBreaks": "LF", + "validateQuoteMarks": "'", + "requireSemicolons": true, + "disallowEmptyBlocks": true, + "disallowKeywordsOnNewLine": ["else"], + "disallowKeywords": ["with"], + "disallowMixedSpacesAndTabs": true, + "disallowMultipleLineBreaks": true, + "disallowMultipleLineStrings": true, + "disallowMultipleVarDecl": "exceptUndefined", + "disallowNewlineBeforeBlockStatements": true, + "disallowOperatorBeforeLineBreak": ["."], + "disallowSpaceBeforeBinaryOperators": [","], + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": true, + "disallowSpaceBeforeComma": true, + "disallowSpaceBeforePostfixUnaryOperators": true, + "disallowSpaceBeforeSemicolon": true, + "disallowSpacesInCallExpression": true, + "disallowSpacesInFunctionDeclaration": { + "beforeOpeningRoundBrace": true + }, + "disallowSpacesInFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowSpacesInsideParentheses": true, + "disallowSpacesInsideParenthesizedExpression": { + "allExcept": [ "{", "}" ] + }, + "disallowTrailingComma": true, + "disallowTrailingWhitespace": true, + "disallowYodaConditions": true, + "requireBlocksOnNewline": true, + "requireCapitalizedConstructors": true, + "requireCommaBeforeLineBreak": true, + "requireCurlyBraces": [ + "for", + "while", + "do", + "try", + "catch" + ], + "requireDotNotation": true, + "requireLineBreakAfterVariableAssignment": true, + "requireLineFeedAtFileEnd": true, + "requirePaddingNewLinesAfterBlocks": true, + "requirePaddingNewLinesAfterUseStrict": true, + "requireParenthesesAroundIIFE": true, + "requireSpaceAfterBinaryOperators": true, + "requireSpaceAfterKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "void", + "while", + "with", + "return", + "typeof" + ], + "requireSpaceBeforeBinaryOperators": true, + "requireSpaceBeforeBlockStatements": true, + "requireSpaceBetweenArguments": true, + "requireSpacesInFunction": { + "beforeOpeningCurlyBrace": true + }, + "requireSpacesInConditionalExpression": true, + "requireSpacesInForStatement": true, + "requireSpacesInFunctionDeclaration": { + "beforeOpeningCurlyBrace": true + }, + "requireSpacesInFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "validateNewlineAfterArrayElements": true, + "validateParameterSeparator": ", ", + "disallowMultipleSpaces": true +} \ No newline at end of file diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index efc2dc17..00000000 --- a/.jshintrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "eqnull": true, - "expr": true, - "indent": 2, - "node": true, - "trailing": true, - "quotmark": "single", - "strict": true, - "undef": true, - "unused": "vars", - "globals": { - "Promise": true - } -} \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 18bc505d..dea05c97 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,10 +10,14 @@ cache: node_js: - "0.10" - "0.12" - - iojs + - "4" + - "5" script: - - npm test + - npm run eslint + - npm run jscs + - npm run test-cov after_script: + - npm install coveralls - cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js deleted file mode 100644 index 6fb4a1ae..00000000 --- a/gulpfile.js +++ /dev/null @@ -1,47 +0,0 @@ -var gulp = require('gulp'); -var $ = require('gulp-load-plugins')(); -var del = require('del'); - -var lib = 'lib/**/*.js'; -var test = 'test/scripts/**/*.js'; - -function mochaStream(){ - return gulp.src('test/index.js') - .pipe($.mocha({ - reporter: 'spec' - })); -} - -gulp.task('coverage', function(){ - return gulp.src(lib) - .pipe($.istanbul()); -}); - -gulp.task('coverage:clean', function(callback){ - del(['coverage/**/*'], callback); -}); - -gulp.task('mocha', ['coverage'], function(){ - return mochaStream() - .pipe($.istanbul.writeReports()); -}); - -gulp.task('mocha:nocov', function(){ - return mochaStream(); -}); - -gulp.task('jshint', function(){ - return gulp.src(lib) - .pipe($.jshint()) - .pipe($.jshint.reporter('jshint-stylish')) - .pipe($.jshint.reporter('fail')); -}); - -gulp.task('watch', function(){ - gulp.watch(lib, ['mocha', 'jshint']); - gulp.watch(['test/index.js', test], ['mocha']); -}); - -gulp.task('test', ['mocha', 'jshint']); - -gulp.task('clean', ['coverage:clean']); \ No newline at end of file diff --git a/lib/database.js b/lib/database.js index 7795a072..b8f79aad 100644 --- a/lib/database.js +++ b/lib/database.js @@ -21,7 +21,7 @@ var extend = util.extend; * @constructor * @module warehouse */ -function Database(options){ +function Database(options) { /** * Database options. * @@ -30,8 +30,9 @@ function Database(options){ */ this.options = extend({ version: 0, - onUpgrade: function(){}, - onDowngrade: function(){} + onUpgrade: function() {}, + + onDowngrade: function() {} }, options); /** @@ -51,7 +52,7 @@ function Database(options){ * @constructor * @private */ - var _Model = this.Model = function(name, schema){ + var _Model = this.Model = function(name, schema) { Model.call(this, name, schema); }; @@ -67,8 +68,8 @@ function Database(options){ * @param {Schema|Object} [schema] * @return {Model} */ -Database.prototype.model = function(name, schema){ - if (this._models[name]){ +Database.prototype.model = function(name, schema) { + if (this._models[name]) { return this._models[name]; } @@ -83,20 +84,20 @@ Database.prototype.model = function(name, schema){ * @param {Function} [callback] * @return {Promise} */ -Database.prototype.load = function(callback){ +Database.prototype.load = function(callback) { var path = this.options.path; var self = this; if (!path) throw new WarehouseError('options.path is required'); - return new Promise(function(resolve, reject){ + return new Promise(function(resolve, reject) { var src = fs.createReadStream(path, {encoding: 'utf8'}); var oldVersion = 0; - var stream = JSONStream.parse([true, true], function(value, keys){ + var stream = JSONStream.parse([true, true], function(value, keys) { switch (keys.shift()){ case 'meta': - if (keys.shift() === 'version'){ + if (keys.shift() === 'version') { oldVersion = value; } @@ -111,15 +112,15 @@ Database.prototype.load = function(callback){ src .pipe(stream) .on('error', reject) - .on('end', function(){ + .on('end', function() { resolve(oldVersion); }); - }).then(function(oldVersion){ + }).then(function(oldVersion) { var newVersion = self.options.version; - if (newVersion > oldVersion){ + if (newVersion > oldVersion) { return self.options.onUpgrade(oldVersion, newVersion); - } else if (newVersion < oldVersion){ + } else if (newVersion < oldVersion) { return self.options.onDowngrade(oldVersion, newVersion); } }).nodeify(callback); @@ -132,13 +133,13 @@ Database.prototype.load = function(callback){ * @param {Function} callback * @return {Promise} */ -Database.prototype.save = function(callback){ +Database.prototype.save = function(callback) { var path = this.options.path; var self = this; if (!path) throw new WarehouseError('options.path is required'); - return new Promise(function(resolve, reject){ + return new Promise(function(resolve, reject) { var stream = fs.createWriteStream(path); // Start @@ -151,13 +152,13 @@ Database.prototype.save = function(callback){ }) + ','); // Export models - var models = self._models, - keys = Object.keys(models), - model, key; + var models = self._models; + var keys = Object.keys(models); + var model, key; stream.write('"models":{'); - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; model = models[key]; @@ -201,4 +202,4 @@ Database.SchemaType = Database.prototype.SchemaType = SchemaType; */ Database.version = pkg.version; -module.exports = Database; \ No newline at end of file +module.exports = Database; diff --git a/lib/document.js b/lib/document.js index 7435404b..cfe7e3ce 100644 --- a/lib/document.js +++ b/lib/document.js @@ -10,8 +10,8 @@ var _ = require('lodash'); * @constructor * @module warehouse */ -function Document(data){ - if (data){ +function Document(data) { + if (data) { var keys = Object.keys(data); var key; @@ -29,7 +29,7 @@ function Document(data){ * @param {Function} [callback] * @return {Promise} */ -Document.prototype.save = function(callback){ +Document.prototype.save = function(callback) { return this._model.save(this, callback); }; @@ -41,7 +41,7 @@ Document.prototype.save = function(callback){ * @param {Function} [callback] * @return {Promise} */ -Document.prototype.update = function(data, callback){ +Document.prototype.update = function(data, callback) { return this._model.updateById(this._id, data, callback); }; @@ -53,7 +53,7 @@ Document.prototype.update = function(data, callback){ * @param {Function} [callback] * @return {Promise} */ -Document.prototype.replace = function(data, callback){ +Document.prototype.replace = function(data, callback) { return this._model.replaceById(this._id, data, callback); }; @@ -64,7 +64,7 @@ Document.prototype.replace = function(data, callback){ * @param {Function} [callback] * @return {Promise} */ -Document.prototype.remove = function(callback){ +Document.prototype.remove = function(callback) { return this._model.removeById(this._id, callback); }; @@ -74,12 +74,12 @@ Document.prototype.remove = function(callback){ * @method toObject * @return {Object} */ -Document.prototype.toObject = function(){ +Document.prototype.toObject = function() { var keys = Object.keys(this); var obj = {}; var key; - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; // Don't deep clone getters in order to avoid "Maximum call stack size // exceeded" error @@ -89,7 +89,7 @@ Document.prototype.toObject = function(){ return obj; }; -function isGetter(obj, key){ +function isGetter(obj, key) { return Object.getOwnPropertyDescriptor(obj, key).get; } @@ -99,7 +99,7 @@ function isGetter(obj, key){ * @method toString * @return {String} */ -Document.prototype.toString = function(){ +Document.prototype.toString = function() { return JSON.stringify(this); }; @@ -110,7 +110,7 @@ Document.prototype.toString = function(){ * @param {String|Object} expr * @return {Document} */ -Document.prototype.populate = function(expr){ +Document.prototype.populate = function(expr) { var stack = this._schema._parsePopulate(expr); return this._model._populate(this, stack); }; diff --git a/lib/error.js b/lib/error.js index 89dd8b13..f79b54bd 100644 --- a/lib/error.js +++ b/lib/error.js @@ -2,7 +2,7 @@ var util = require('./util'); -function WarehouseError(msg){ +function WarehouseError(msg) { Error.call(this); Error.captureStackTrace && Error.captureStackTrace(this, WarehouseError); @@ -12,4 +12,4 @@ function WarehouseError(msg){ util.inherits(WarehouseError, Error); -module.exports = WarehouseError; \ No newline at end of file +module.exports = WarehouseError; diff --git a/lib/error/population.js b/lib/error/population.js index d2e60877..6dfee0a4 100644 --- a/lib/error/population.js +++ b/lib/error/population.js @@ -3,7 +3,7 @@ var util = require('../util'); var WarehouseError = require('../error'); -function PopulationError(msg){ +function PopulationError(msg) { Error.call(this); Error.captureStackTrace && Error.captureStackTrace(this, PopulationError); @@ -13,4 +13,4 @@ function PopulationError(msg){ util.inherits(PopulationError, WarehouseError); -module.exports = PopulationError; \ No newline at end of file +module.exports = PopulationError; diff --git a/lib/error/validation.js b/lib/error/validation.js index 67406849..29dd38a6 100644 --- a/lib/error/validation.js +++ b/lib/error/validation.js @@ -3,7 +3,7 @@ var util = require('../util'); var WarehouseError = require('../error'); -function ValidationError(msg){ +function ValidationError(msg) { Error.call(this); Error.captureStackTrace && Error.captureStackTrace(this, ValidationError); @@ -13,4 +13,4 @@ function ValidationError(msg){ util.inherits(ValidationError, WarehouseError); -module.exports = ValidationError; \ No newline at end of file +module.exports = ValidationError; diff --git a/lib/model.js b/lib/model.js index 99797066..8fdda17b 100644 --- a/lib/model.js +++ b/lib/model.js @@ -30,22 +30,22 @@ var isArray = Array.isArray; * @extends EventEmitter * @module warehouse */ -function Model(name, schema_){ +function Model(name, schema_) { EventEmitter.call(this); var schema, i, len, key; // Define schema - if (schema_ instanceof Schema){ + if (schema_ instanceof Schema) { schema = schema_; - } else if (typeof schema_ === 'object'){ + } else if (typeof schema_ === 'object') { schema = new Schema(schema_); } else { schema = new Schema(); } // Set `_id` path for schema - if (!schema.path('_id')){ + if (!schema.path('_id')) { schema.path('_id', {type: Types.CUID, required: true}); } @@ -97,7 +97,7 @@ function Model(name, schema_){ * @constructor * @private */ - var _Document = this.Document = function(data){ + var _Document = this.Document = function(data) { Document.call(this, data); // Apply getters @@ -117,7 +117,7 @@ function Model(name, schema_){ * @constructor * @private */ - var _Query = this.Query = function(data){ + var _Query = this.Query = function(data) { Query.call(this, data); }; @@ -129,7 +129,7 @@ function Model(name, schema_){ var statics = schema.statics; var staticKeys = Object.keys(statics); - for (i = 0, len = staticKeys.length; i < len; i++){ + for (i = 0, len = staticKeys.length; i < len; i++) { key = staticKeys[i]; this[key] = statics[key]; } @@ -138,7 +138,7 @@ function Model(name, schema_){ var methods = schema.methods; var methodKeys = Object.keys(methods); - for (i = 0, len = methodKeys.length; i < len; i++){ + for (i = 0, len = methodKeys.length; i < len; i++) { key = methodKeys[i]; _Document.prototype[key] = methods[key]; } @@ -153,7 +153,7 @@ util.inherits(Model, EventEmitter); * @param {Object} data * @return {Document} */ -Model.prototype.new = function(data){ +Model.prototype.new = function(data) { return new this.Document(data); }; @@ -166,7 +166,7 @@ Model.prototype.new = function(data){ * @param {Boolean} [options.lean=false] Returns a plain JavaScript object * @return {Document|Object} */ -Model.prototype.findById = function(id, options_){ +Model.prototype.findById = function(id, options_) { var raw = this.data[id]; if (!raw) return; @@ -185,11 +185,11 @@ Model.prototype.findById = function(id, options_){ */ Model.prototype.get = Model.prototype.findById; -function execHooks(schema, type, event, data){ +function execHooks(schema, type, event, data) { var hooks = schema.hooks[type][event]; if (!hooks.length) return Promise.resolve(data); - return Promise.each(hooks, function(hook){ + return Promise.each(hooks, function(hook) { return hook(data); }).thenReturn(data); } @@ -202,12 +202,12 @@ function execHooks(schema, type, event, data){ * @param {Function} [callback] * @return {Promise} */ -Model.prototype.insertOne = function(data_, callback){ +Model.prototype.insertOne = function(data_, callback) { var self = this; var schema = this.schema; var result; - return this._queue.push(function(){ + return this._queue.push(function() { return new Promise(function(resolve, reject) { // Apply getters var data = data_ instanceof self.Document ? data_ : self.new(data_); @@ -223,7 +223,7 @@ Model.prototype.insertOne = function(data_, callback){ } resolve(data); - }).then(function(data){ + }).then(function(data) { // Apply setters result = data.toObject(); var err = schema._applySetters(result); @@ -232,7 +232,7 @@ Model.prototype.insertOne = function(data_, callback){ // Pre-hooks return execHooks(schema, 'pre', 'save', data); - }).then(function(data){ + }).then(function(data) { // Insert data self.data[data._id] = result; self.length++; @@ -244,7 +244,7 @@ Model.prototype.insertOne = function(data_, callback){ */ self.emit('insert', data); return data; - }).then(function(data){ + }).then(function(data) { return execHooks(schema, 'post', 'save', data); }); }).nodeify(callback); @@ -258,16 +258,16 @@ Model.prototype.insertOne = function(data_, callback){ * @param {Function} [callback] * @return {Promise} */ -Model.prototype.insert = function(data, callback){ - if (isArray(data)){ +Model.prototype.insert = function(data, callback) { + if (isArray(data)) { var self = this; - return Promise.map(data, function(item){ + return Promise.map(data, function(item) { return self.insertOne(item); }).nodeify(callback); - } else { - return this.insertOne(data, callback); } + + return this.insertOne(data, callback); }; /** @@ -278,14 +278,14 @@ Model.prototype.insert = function(data, callback){ * @param {Function} [callback] * @return {Promise} */ -Model.prototype.save = function(data, callback){ +Model.prototype.save = function(data, callback) { var id = data._id; - if (id && this.data[id]){ + if (id && this.data[id]) { return this.replaceById(id, data, callback); - } else { - return this.insertOne(data, callback); } + + return this.insertOne(data, callback); }; /** @@ -297,16 +297,16 @@ Model.prototype.save = function(data, callback){ * @return {Promise} * @private */ -Model.prototype._updateWithStack = function(id, stack){ +Model.prototype._updateWithStack = function(id, stack) { var self = this; var schema = self.schema; var result; - return this._queue.push(function(){ - return new Promise(function(resolve, reject){ + return this._queue.push(function() { + return new Promise(function(resolve, reject) { var data = self.data[id]; - if (!data){ + if (!data) { return reject(new WarehouseError('ID `' + id + '` does not exist')); } @@ -314,7 +314,7 @@ Model.prototype._updateWithStack = function(id, stack){ var result = _.cloneDeep(data); // Update - for (var i = 0, len = stack.length; i < len; i++){ + for (var i = 0, len = stack.length; i < len; i++) { stack[i](result); } @@ -322,7 +322,7 @@ Model.prototype._updateWithStack = function(id, stack){ var doc = self.new(result); resolve(doc); - }).then(function(data){ + }).then(function(data) { // Apply setters result = data.toObject(); var err = schema._applySetters(result); @@ -331,7 +331,7 @@ Model.prototype._updateWithStack = function(id, stack){ // Pre-hooks return execHooks(schema, 'pre', 'save', data); - }).then(function(data){ + }).then(function(data) { // Update data self.data[id] = result; @@ -342,7 +342,7 @@ Model.prototype._updateWithStack = function(id, stack){ */ self.emit('update', data); return data; - }).then(function(data){ + }).then(function(data) { return execHooks(schema, 'post', 'save', data); }); }); @@ -357,7 +357,7 @@ Model.prototype._updateWithStack = function(id, stack){ * @param {Function} [callback] * @return {Promise} */ -Model.prototype.updateById = function(id, update, callback){ +Model.prototype.updateById = function(id, update, callback) { var stack = this.schema._parseUpdate(update); return this._updateWithStack(id, stack).nodeify(callback); @@ -372,7 +372,7 @@ Model.prototype.updateById = function(id, update, callback){ * @param {Function} [callback] * @return {Promise} */ -Model.prototype.update = function(query, data, callback){ +Model.prototype.update = function(query, data, callback) { return this.find(query).update(data, callback); }; @@ -385,14 +385,14 @@ Model.prototype.update = function(query, data, callback){ * @param {Function} [callback] * @return {Promise} */ -Model.prototype.replaceById = function(id, data_, callback){ +Model.prototype.replaceById = function(id, data_, callback) { var self = this; var schema = this.schema; var result; - return this._queue.push(function(){ - return new Promise(function(resolve, reject){ - if (!self.data[id]){ + return this._queue.push(function() { + return new Promise(function(resolve, reject) { + if (!self.data[id]) { return reject(new WarehouseError('ID `' + id + '` does not exist')); } @@ -402,7 +402,7 @@ Model.prototype.replaceById = function(id, data_, callback){ var data = data instanceof self.Document ? data_ : self.new(data_); resolve(data); - }).then(function(data){ + }).then(function(data) { // Apply setters result = data.toObject(); var err = schema._applySetters(result); @@ -411,13 +411,13 @@ Model.prototype.replaceById = function(id, data_, callback){ // Pre-hooks return execHooks(schema, 'pre', 'save', data); - }).then(function(data){ + }).then(function(data) { // Replace data self.data[id] = result; self.emit('update', data); return data; - }).then(function(data){ + }).then(function(data) { return execHooks(schema, 'post', 'save', data); }); }).nodeify(callback); @@ -432,7 +432,7 @@ Model.prototype.replaceById = function(id, data_, callback){ * @param {Function} [callback] * @return {Promise} */ -Model.prototype.replace = function(query, data, callback){ +Model.prototype.replace = function(query, data, callback) { return this.find(query).replace(data, callback); }; @@ -444,22 +444,22 @@ Model.prototype.replace = function(query, data, callback){ * @param {Function} [callback] * @return {Promise} */ -Model.prototype.removeById = function(id, callback){ +Model.prototype.removeById = function(id, callback) { var self = this; var schema = this.schema; - return this._queue.push(function(){ - return new Promise(function(resolve, reject){ + return this._queue.push(function() { + return new Promise(function(resolve, reject) { var data = self.data[id]; - if (!data){ + if (!data) { return reject(new WarehouseError('ID `' + id + '` does not exist')); } resolve(data); - }).then(function(data){ // Pre-hooks + }).then(function(data) { // Pre-hooks return execHooks(schema, 'pre', 'remove', data); - }).then(function(data){ // Removes data + }).then(function(data) { // Removes data self.data[id] = null; self.length--; @@ -470,7 +470,7 @@ Model.prototype.removeById = function(id, callback){ */ self.emit('remove', data); return data; - }).then(function(data){ + }).then(function(data) { return execHooks(schema, 'post', 'remove', data); }); }).nodeify(callback); @@ -484,7 +484,7 @@ Model.prototype.removeById = function(id, callback){ * @param {Object} [callback] * @return {Promise} */ -Model.prototype.remove = function(query, callback){ +Model.prototype.remove = function(query, callback) { return this.find(query).remove(callback); }; @@ -493,7 +493,7 @@ Model.prototype.remove = function(query, callback){ * * @method destroy */ -Model.prototype.destroy = function(){ +Model.prototype.destroy = function() { this._database._models[this.name] = null; }; @@ -503,7 +503,7 @@ Model.prototype.destroy = function(){ * @method count * @return {Number} */ -Model.prototype.count = function(){ +Model.prototype.count = function() { return this.length; }; @@ -521,12 +521,12 @@ Model.prototype.size = Model.prototype.count; * @param {Function} iterator * @param {Object} [options] See {% crosslink Model.findById %}. */ -Model.prototype.forEach = function(iterator, options){ +Model.prototype.forEach = function(iterator, options) { var keys = Object.keys(this.data); var num = 0; var data; - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { data = this.findById(keys[i], options); if (data) iterator(data, num++); } @@ -546,10 +546,10 @@ Model.prototype.each = Model.prototype.forEach; * @param {Object} [options] See {% crosslink Model.findById %}. * @return {Array} */ -Model.prototype.toArray = function(options){ +Model.prototype.toArray = function(options) { var result = new Array(this.length); - this.forEach(function(item, i){ + this.forEach(function(item, i) { result[i] = item; }, options); @@ -567,7 +567,7 @@ Model.prototype.toArray = function(options){ * @param {Boolean} [options.lean=false] Returns a plain JavaScript object. * @return {Query|Array} */ -Model.prototype.find = function(query, options_){ +Model.prototype.find = function(query, options_) { var options = options_ || {}; var filter = this.schema._execQuery(query); var keys = Object.keys(this.data); @@ -578,12 +578,12 @@ Model.prototype.find = function(query, options_){ var arr = []; var key, item; - for (var i = 0; limit && i < len; i++){ + for (var i = 0; limit && i < len; i++) { key = keys[i]; item = data[key]; - if (item && filter(item)){ - if (skip){ + if (item && filter(item)) { + if (skip) { skip--; } else { arr.push(this.findById(key, options)); @@ -605,7 +605,7 @@ Model.prototype.find = function(query, options_){ * @param {Boolean} [options.lean=false] Returns a plain JavaScript object. * @return {Document|Object} */ -Model.prototype.findOne = function(query, options_){ +Model.prototype.findOne = function(query, options_) { var options = options_ || {}; options.limit = 1; @@ -621,7 +621,7 @@ Model.prototype.findOne = function(query, options_){ * @param {String|Number} [order] * @return {Query} */ -Model.prototype.sort = function(orderby, order){ +Model.prototype.sort = function(orderby, order) { var sort = parseArgs(orderby, order); var fn = this.schema._execSort(sort); @@ -637,13 +637,13 @@ Model.prototype.sort = function(orderby, order){ * @param {Object} [options] See {% crosslink Model.findById %}. * @return {Document|Object} */ -Model.prototype.eq = function(i_, options){ +Model.prototype.eq = function(i_, options) { var index = i_ < 0 ? this.length + i_ : i_; var data = this.data; var keys = Object.keys(data); var key, item; - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; item = data[key]; @@ -664,7 +664,7 @@ Model.prototype.eq = function(i_, options){ * @param {Object} [options] See {% crosslink Model.findById %}. * @return {Document|Object} */ -Model.prototype.first = function(options){ +Model.prototype.first = function(options) { return this.eq(0, options); }; @@ -675,7 +675,7 @@ Model.prototype.first = function(options){ * @param {Object} [options] See {% crosslink Model.findById %}. * @return {Document|Object} */ -Model.prototype.last = function(options){ +Model.prototype.last = function(options) { return this.eq(-1, options); }; @@ -687,7 +687,7 @@ Model.prototype.last = function(options){ * @param {Number} [end] * @return {Query} */ -Model.prototype.slice = function(start_, end_){ +Model.prototype.slice = function(start_, end_) { var total = this.length; var start = start_ | 0; @@ -707,11 +707,11 @@ Model.prototype.slice = function(start_, end_){ var num = 0; var data; - for (var i = 0; num < len && i < keysLen; i++){ + for (var i = 0; num < len && i < keysLen; i++) { data = this.findById(keys[i]); if (!data) continue; - if (start){ + if (start) { start--; } else { arr[num++] = data; @@ -728,7 +728,7 @@ Model.prototype.slice = function(start_, end_){ * @param {Number} i * @return {Query} */ -Model.prototype.limit = function(i){ +Model.prototype.limit = function(i) { return this.slice(0, i); }; @@ -739,7 +739,7 @@ Model.prototype.limit = function(i){ * @param {Number} i * @return {Query} */ -Model.prototype.skip = function(i){ +Model.prototype.skip = function(i) { return this.slice(i); }; @@ -749,7 +749,7 @@ Model.prototype.skip = function(i){ * @method reverse * @return {Query} */ -Model.prototype.reverse = function(){ +Model.prototype.reverse = function() { return new this.Query(reverse(this.toArray())); }; @@ -759,7 +759,7 @@ Model.prototype.reverse = function(){ * @method shuffle * @return {Query} */ -Model.prototype.shuffle = function(){ +Model.prototype.shuffle = function() { return new this.Query(shuffle(this.toArray())); }; @@ -778,10 +778,10 @@ Model.prototype.random = Model.prototype.shuffle; * @param {Object} [options] * @return {Array} */ -Model.prototype.map = function(iterator, options){ +Model.prototype.map = function(iterator, options) { var result = new Array(this.length); - this.forEach(function(item, i){ + this.forEach(function(item, i) { result[i] = iterator(item, i); }, options); @@ -797,12 +797,12 @@ Model.prototype.map = function(iterator, options){ * @param {*} [initial] By default, the initial value is the first document. * @return {*} */ -Model.prototype.reduce = function(iterator, initial){ +Model.prototype.reduce = function(iterator, initial) { var arr = this.toArray(); var len = this.length; var i, result; - if (initial === undefined){ + if (initial === undefined) { i = 1; result = arr[0]; } else { @@ -810,7 +810,7 @@ Model.prototype.reduce = function(iterator, initial){ result = initial; } - for (; i < len; i++){ + for (; i < len; i++) { result = iterator(result, arr[i], i); } @@ -826,12 +826,12 @@ Model.prototype.reduce = function(iterator, initial){ * @param {*} [initial] By default, the initial value is the last document. * @return {*} */ -Model.prototype.reduceRight = function(iterator, initial){ +Model.prototype.reduceRight = function(iterator, initial) { var arr = this.toArray(); var len = this.length; var i, result; - if (initial === undefined){ + if (initial === undefined) { i = len - 2; result = arr[len - 1]; } else { @@ -839,7 +839,7 @@ Model.prototype.reduceRight = function(iterator, initial){ result = initial; } - for (; i >= 0; i--){ + for (; i >= 0; i--) { result = iterator(result, arr[i], i); } @@ -855,10 +855,10 @@ Model.prototype.reduceRight = function(iterator, initial){ * @param {Object} [options] * @return {Query} */ -Model.prototype.filter = function(iterator, options){ +Model.prototype.filter = function(iterator, options) { var arr = []; - this.forEach(function(item, i){ + this.forEach(function(item, i) { if (iterator(item, i)) arr.push(item); }, options); @@ -873,7 +873,7 @@ Model.prototype.filter = function(iterator, options){ * @param {Function} iterator * @return {Boolean} */ -Model.prototype.every = function(iterator){ +Model.prototype.every = function(iterator) { var keys = Object.keys(this.data); var len = keys.length; var num = 0; @@ -881,10 +881,10 @@ Model.prototype.every = function(iterator){ if (!len) return true; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { data = this.findById(keys[i]); - if (data){ + if (data) { if (!iterator(data, num++)) return false; } } @@ -900,7 +900,7 @@ Model.prototype.every = function(iterator){ * @param {Function} iterator * @return {Boolean} */ -Model.prototype.some = function(iterator){ +Model.prototype.some = function(iterator) { var keys = Object.keys(this.data); var len = keys.length; var num = 0; @@ -908,10 +908,10 @@ Model.prototype.some = function(iterator){ if (!len) return false; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { data = this.findById(keys[i]); - if (data){ + if (data) { if (iterator(data, num++)) return true; } } @@ -929,12 +929,12 @@ Model.prototype.some = function(iterator){ * @return {Function} * @private */ -Model.prototype._populateGetter = function(data, model, options){ +Model.prototype._populateGetter = function(data, model, options) { var hasCache = false; var cache; - return function(){ - if (!hasCache){ + return function() { + if (!hasCache) { cache = model.findById(data); hasCache = true; } @@ -953,36 +953,36 @@ Model.prototype._populateGetter = function(data, model, options){ * @return {Function} * @private */ -Model.prototype._populateGetterArray = function(data, model, options){ +Model.prototype._populateGetterArray = function(data, model, options) { var Query = model.Query; var hasCache = false; var cache; - return function(){ - if (!hasCache){ + return function() { + if (!hasCache) { var arr = []; - for (var i = 0, len = data.length; i < len; i++){ + for (var i = 0, len = data.length; i < len; i++) { arr.push(model.findById(data[i])); } - if (options.match){ + if (options.match) { cache = new Query(arr).find(options.match, options); - } else if (options.skip){ - if (options.limit){ + } else if (options.skip) { + if (options.limit) { arr = arr.slice(options.skip, options.skip + options.limit); } else { arr = arr.slice(options.skip); } cache = new Query(arr); - } else if (options.limit){ + } else if (options.limit) { cache = new Query(arr.slice(0, options.limit)); } else { cache = new Query(arr); } - if (options.sort){ + if (options.sort) { cache = cache.sort(options.sort); } @@ -1002,22 +1002,22 @@ Model.prototype._populateGetterArray = function(data, model, options){ * @return {Object} * @private */ -Model.prototype._populate = function(data, stack){ +Model.prototype._populate = function(data, stack) { var models = this._database._models; var item, model, path, prop; - for (var i = 0, len = stack.length; i < len; i++){ + for (var i = 0, len = stack.length; i < len; i++) { item = stack[i]; model = models[item.model]; - if (!model){ + if (!model) { throw new PopulationError('Model `' + item.model + '` does not exist'); } path = item.path; prop = getProp(data, path); - if (isArray(prop)){ + if (isArray(prop)) { setGetter(data, path, this._populateGetterArray(prop, model, item)); } else { setGetter(data, path, this._populateGetter(prop, model, item)); @@ -1034,14 +1034,14 @@ Model.prototype._populate = function(data, stack){ * @param {String|Object} path * @return {Query} */ -Model.prototype.populate = function(path){ +Model.prototype.populate = function(path) { if (!path) throw new TypeError('path is required'); var stack = this.schema._parsePopulate(path); var arr = new Array(this.length); var self = this; - this.forEach(function(item, i){ + this.forEach(function(item, i) { arr[i] = self._populate(item, stack); }); @@ -1055,13 +1055,13 @@ Model.prototype.populate = function(path){ * @param {Array} arr * @private */ -Model.prototype._import = function(arr){ +Model.prototype._import = function(arr) { var len = arr.length; var data = this.data; var schema = this.schema; var item; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { item = arr[i]; data[item._id] = schema._parseDatabase(item); } @@ -1076,15 +1076,15 @@ Model.prototype._import = function(arr){ * @return {String} * @private */ -Model.prototype._export = function(){ +Model.prototype._export = function() { var arr = new Array(this.length); var schema = this.schema; - this.forEach(function(item, i){ + this.forEach(function(item, i) { arr[i] = schema._exportDatabase(item); }, {lean: true}); return JSON.stringify(arr); }; -module.exports = Model; \ No newline at end of file +module.exports = Model; diff --git a/lib/query.js b/lib/query.js index ba5d715f..2758671b 100644 --- a/lib/query.js +++ b/lib/query.js @@ -16,7 +16,7 @@ var parseArgs = util.parseArgs; * @constructor * @module warehouse */ -function Query(data){ +function Query(data) { /** * Data storage. * @@ -39,7 +39,7 @@ function Query(data){ * @method count * @return Number */ -Query.prototype.count = function(){ +Query.prototype.count = function() { return this.length; }; @@ -56,10 +56,10 @@ Query.prototype.size = Query.prototype.count; * @method forEach * @param {Function} iterator */ -Query.prototype.forEach = function(iterator){ +Query.prototype.forEach = function(iterator) { var data = this.data; - for (var i = 0, len = this.length; i < len; i++){ + for (var i = 0, len = this.length; i < len; i++) { iterator(data[i], i); } }; @@ -77,7 +77,7 @@ Query.prototype.each = Query.prototype.forEach; * @method toArray * @return {Array} */ -Query.prototype.toArray = function(){ +Query.prototype.toArray = function() { return this.data; }; @@ -89,7 +89,7 @@ Query.prototype.toArray = function(){ * @param {Number} i * @return {Document|Object} */ -Query.prototype.eq = function(i){ +Query.prototype.eq = function(i) { var index = i < 0 ? this.length + i : i; return this.data[index]; }; @@ -100,7 +100,7 @@ Query.prototype.eq = function(i){ * @method first * @return {Document|Object} */ -Query.prototype.first = function(){ +Query.prototype.first = function() { return this.eq(0); }; @@ -110,7 +110,7 @@ Query.prototype.first = function(){ * @method last * @return {Document|Object} */ -Query.prototype.last = function(){ +Query.prototype.last = function() { return this.eq(-1); }; @@ -122,7 +122,7 @@ Query.prototype.last = function(){ * @param {Number} [end] * @return {Query} */ -Query.prototype.slice = function(start, end){ +Query.prototype.slice = function(start, end) { return new this.constructor(this.data.slice(start, end)); }; @@ -133,7 +133,7 @@ Query.prototype.slice = function(start, end){ * @param {Number} i * @return {Query} */ -Query.prototype.limit = function(i){ +Query.prototype.limit = function(i) { return this.slice(0, i); }; @@ -144,7 +144,7 @@ Query.prototype.limit = function(i){ * @param {Number} i * @return {Query} */ -Query.prototype.skip = function(i){ +Query.prototype.skip = function(i) { return this.slice(i); }; @@ -154,7 +154,7 @@ Query.prototype.skip = function(i){ * @method reverse * @return {Query} */ -Query.prototype.reverse = function(){ +Query.prototype.reverse = function() { return new this.constructor(reverse(cloneArray(this.data))); }; @@ -164,7 +164,7 @@ Query.prototype.reverse = function(){ * @method shuffle * @return {Query} */ -Query.prototype.shuffle = function(){ +Query.prototype.shuffle = function() { return new this.constructor(shuffle(cloneArray(this.data))); }; @@ -186,7 +186,7 @@ Query.prototype.random = Query.prototype.shuffle; * @param {Boolean} [options.lean=false] Returns a plain JavaScript object. * @return {Query|Array} */ -Query.prototype.find = function(query, options_){ +Query.prototype.find = function(query, options_) { var options = options_ || {}; var filter = this._schema._execQuery(query); var data = this.data; @@ -197,11 +197,11 @@ Query.prototype.find = function(query, options_){ var arr = []; var item; - for (; limit && i < len; i++){ + for (; limit && i < len; i++) { item = data[i]; - if (filter(item)){ - if (skip){ + if (filter(item)) { + if (skip) { skip--; } else { arr.push(item); @@ -223,7 +223,7 @@ Query.prototype.find = function(query, options_){ * @param {Boolean} [options.lean=false] Returns a plain JavaScript object. * @return {Document|Object} */ -Query.prototype.findOne = function(query, options_){ +Query.prototype.findOne = function(query, options_) { var options = options_ || {}; options.limit = 1; @@ -250,7 +250,7 @@ Query.prototype.findOne = function(query, options_){ * @param {String|Number} [order] * @return {Query} */ -Query.prototype.sort = function(orderby, order){ +Query.prototype.sort = function(orderby, order) { var sort = parseArgs(orderby, order); var fn = this._schema._execSort(sort); @@ -264,12 +264,12 @@ Query.prototype.sort = function(orderby, order){ * @param {Function} iterator * @return {Array} */ -Query.prototype.map = function(iterator){ +Query.prototype.map = function(iterator) { var len = this.length; var result = new Array(len); var data = this.data; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { result[i] = iterator(data[i], i); } @@ -285,12 +285,12 @@ Query.prototype.map = function(iterator){ * @param {*} [initial] By default, the initial value is the first document. * @return {*} */ -Query.prototype.reduce = function(iterator, initial){ +Query.prototype.reduce = function(iterator, initial) { var len = this.length; var data = this.data; var result, i; - if (initial === undefined){ + if (initial === undefined) { i = 1; result = data[0]; } else { @@ -298,7 +298,7 @@ Query.prototype.reduce = function(iterator, initial){ result = initial; } - for (; i < len; i++){ + for (; i < len; i++) { result = iterator(result, data[i], i); } @@ -314,12 +314,12 @@ Query.prototype.reduce = function(iterator, initial){ * @param {*} [initial] By default, the initial value is the last document. * @return {*} */ -Query.prototype.reduceRight = function(iterator, initial){ +Query.prototype.reduceRight = function(iterator, initial) { var len = this.length; var data = this.data; var result, i; - if (initial === undefined){ + if (initial === undefined) { i = len - 2; result = data[len - 1]; } else { @@ -327,7 +327,7 @@ Query.prototype.reduceRight = function(iterator, initial){ result = initial; } - for (; i >= 0; i--){ + for (; i >= 0; i--) { result = iterator(result, data[i], i); } @@ -342,12 +342,12 @@ Query.prototype.reduceRight = function(iterator, initial){ * @param {Function} iterator * @return {Query} */ -Query.prototype.filter = function(iterator){ +Query.prototype.filter = function(iterator) { var data = this.data; var arr = []; var item; - for (var i = 0, len = this.length; i < len; i++){ + for (var i = 0, len = this.length; i < len; i++) { item = data[i]; if (iterator(item, i)) arr.push(item); } @@ -363,10 +363,10 @@ Query.prototype.filter = function(iterator){ * @param {Function} iterator * @return {Boolean} */ -Query.prototype.every = function(iterator){ +Query.prototype.every = function(iterator) { var data = this.data; - for (var i = 0, len = data.length; i < len; i++){ + for (var i = 0, len = data.length; i < len; i++) { if (!iterator(data[i], i)) return false; } @@ -381,10 +381,10 @@ Query.prototype.every = function(iterator){ * @param {Function} iterator * @return {Boolean} */ -Query.prototype.some = function(iterator){ +Query.prototype.some = function(iterator) { var data = this.data; - for (var i = 0, len = data.length; i < len; i++){ + for (var i = 0, len = data.length; i < len; i++) { if (iterator(data[i], i)) return true; } @@ -399,11 +399,11 @@ Query.prototype.some = function(iterator){ * @param {Function} [callback] * @return {Promise} */ -Query.prototype.update = function(data, callback){ +Query.prototype.update = function(data, callback) { var model = this._model; var stack = this._schema._parseUpdate(data); - return Promise.map(this.data, function(item){ + return Promise.map(this.data, function(item) { return model._updateWithStack(item._id, stack); }).nodeify(callback); }; @@ -416,10 +416,10 @@ Query.prototype.update = function(data, callback){ * @param {Function} [callback] * @return {Promise} */ -Query.prototype.replace = function(data, callback){ +Query.prototype.replace = function(data, callback) { var model = this._model; - return Promise.map(this.data, function(item){ + return Promise.map(this.data, function(item) { return model.replaceById(item._id, data); }).nodeify(callback); }; @@ -431,10 +431,10 @@ Query.prototype.replace = function(data, callback){ * @param {Function} [callback] * @return {Promise} */ -Query.prototype.remove = function(callback){ +Query.prototype.remove = function(callback) { var model = this._model; - return Promise.map(this.data, function(item){ + return Promise.map(this.data, function(item) { return model.removeById(item._id); }).nodeify(callback); }; @@ -446,16 +446,16 @@ Query.prototype.remove = function(callback){ * @param {String|Object} expr * @return {Query} */ -Query.prototype.populate = function(expr){ +Query.prototype.populate = function(expr) { var stack = this._schema._parsePopulate(expr); var data = this.data; var model = this._model; - for (var i = 0, len = this.length; i < len; i++){ + for (var i = 0, len = this.length; i < len; i++) { data[i] = model._populate(data[i], stack); } return this; }; -module.exports = Query; \ No newline at end of file +module.exports = Query; diff --git a/lib/queue.js b/lib/queue.js index 6a4b20a8..ca74dda3 100644 --- a/lib/queue.js +++ b/lib/queue.js @@ -9,7 +9,7 @@ var Promise = require('bluebird'); * @constructor * @module warehouse */ -function Queue(){ +function Queue() { /** * The queue of tasks. * @@ -34,10 +34,10 @@ function Queue(){ * @param {Function} fn * @return {Promise} */ -Queue.prototype.push = function(fn){ +Queue.prototype.push = function(fn) { var self = this; - return new Promise(function(resolve, reject){ + return new Promise(function(resolve, reject) { self.tasks.push({ fn: Promise.method(fn), resolve: resolve, @@ -54,7 +54,7 @@ Queue.prototype.push = function(fn){ * @method _dequeue * @private */ -Queue.prototype._dequeue = function(){ +Queue.prototype._dequeue = function() { var tasks = this.tasks; if (this.pendingTasks || !tasks.length) return; @@ -64,14 +64,15 @@ Queue.prototype._dequeue = function(){ this.pendingTasks++; - task.fn().then(function(data){ + task.fn().then(function(data) { task.resolve(data); - }, function(err){ + }, function(err) { + task.reject(err); - }).finally(function(){ + }).finally(function() { self.pendingTasks--; self._dequeue(); }); }; -module.exports = Queue; \ No newline at end of file +module.exports = Queue; diff --git a/lib/schema.js b/lib/schema.js index dc799ff6..6fb9ca25 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -28,7 +28,7 @@ var builtinTypes = { * @constructor * @module warehouse */ -function Schema(schema){ +function Schema(schema) { /** * Schema paths. * @@ -83,7 +83,7 @@ function Schema(schema){ export: [] }; - if (schema){ + if (schema) { this.add(schema); } } @@ -95,7 +95,7 @@ function Schema(schema){ * @param {Object} schema * @param {String} prefix_ */ -Schema.prototype.add = function(schema, prefix_){ +Schema.prototype.add = function(schema, prefix_) { var prefix = prefix_ || ''; var keys = Object.keys(schema); var len = keys.length; @@ -103,7 +103,7 @@ Schema.prototype.add = function(schema, prefix_){ if (!len) return; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { key = keys[i]; value = schema[key]; @@ -111,15 +111,15 @@ Schema.prototype.add = function(schema, prefix_){ } }; -function getSchemaType(name, options){ +function getSchemaType(name, options) { var Type = options.type || options; var typeName = Type.name; - if (builtinTypes[typeName]){ + if (builtinTypes[typeName]) { return new Types[typeName](name, options); - } else { - return new Type(name, options); } + + return new Type(name, options); } /** @@ -130,15 +130,15 @@ function getSchemaType(name, options){ * @param {*} obj * @return {SchemaType} */ -Schema.prototype.path = function(name, obj){ - if (obj == null){ +Schema.prototype.path = function(name, obj) { + if (obj == null) { return this.paths[name]; } var type; var nested = false; - if (obj instanceof SchemaType){ + if (obj instanceof SchemaType) { type = obj; } else { switch (typeof obj){ @@ -147,9 +147,9 @@ Schema.prototype.path = function(name, obj){ break; case 'object': - if (obj.type){ + if (obj.type) { type = getSchemaType(name, obj); - } else if (isArray(obj)){ + } else if (isArray(obj)) { type = new Types.Array(name, { child: obj.length ? getSchemaType(name, obj[0]) : new SchemaType(name) }); @@ -179,51 +179,51 @@ Schema.prototype.path = function(name, obj){ * @param {SchemaType} type * @private */ -Schema.prototype._updateStack = function(name, type){ +Schema.prototype._updateStack = function(name, type) { var stacks = this.stacks; - stacks.getter.push(function(data){ + stacks.getter.push(function(data) { var value = getProp(data, name); var result = type.cast(value, data); if (result instanceof Error) return result; - if (result !== undefined){ + if (result !== undefined) { setProp(data, name, result); } }); - stacks.setter.push(function(data){ + stacks.setter.push(function(data) { var value = getProp(data, name); var result = type.validate(value, data); if (result instanceof Error) return result; - if (result !== undefined){ + if (result !== undefined) { setProp(data, name, result); } else { delProp(data, name); } }); - stacks.import.push(function(data){ + stacks.import.push(function(data) { var value = getProp(data, name); var result = type.parse(value, data); if (result instanceof Error) return result; - if (result !== undefined){ + if (result !== undefined) { setProp(data, name, result); } }); - stacks.export.push(function(data){ + stacks.export.push(function(data) { var value = getProp(data, name); var result = type.value(value, data); if (result instanceof Error) return result; - if (result !== undefined){ + if (result !== undefined) { setProp(data, name, result); } else { delProp(data, name); @@ -239,7 +239,7 @@ Schema.prototype._updateStack = function(name, type){ * @param {Function} [getter] * @return {SchemaType.Virtual} */ -Schema.prototype.virtual = function(name, getter){ +Schema.prototype.virtual = function(name, getter) { var virtual = new Types.Virtual(name, {}); if (getter) virtual.get(getter); @@ -248,18 +248,18 @@ Schema.prototype.virtual = function(name, getter){ return virtual; }; -function checkHookType(type){ - if (type !== 'save' && type !== 'remove'){ +function checkHookType(type) { + if (type !== 'save' && type !== 'remove') { throw new TypeError('Hook type must be `save` or `remove`!'); } } -function hookWrapper(fn){ - if (fn.length > 1){ - return function(data){ - return new Promise(function(resolve, reject){ - fn(data, function(err){ - if (err){ +function hookWrapper(fn) { + if (fn.length > 1) { + return function(data) { + return new Promise(function(resolve, reject) { + fn(data, function(err) { + if (err) { reject(err); } else { resolve(); @@ -267,9 +267,9 @@ function hookWrapper(fn){ }); }); }; - } else { - return Promise.method(fn); } + + return Promise.method(fn); } /** @@ -279,7 +279,7 @@ function hookWrapper(fn){ * @param {String} type Hook type. One of `save` or `remove`. * @param {Function} fn */ -Schema.prototype.pre = function(type, fn){ +Schema.prototype.pre = function(type, fn) { checkHookType(type); if (typeof fn !== 'function') throw new TypeError('Hook must be a function!'); @@ -294,7 +294,7 @@ Schema.prototype.pre = function(type, fn){ * @param {Function} fn */ -Schema.prototype.post = function(type, fn){ +Schema.prototype.post = function(type, fn) { checkHookType(type); if (typeof fn !== 'function') throw new TypeError('Hook must be a function!'); @@ -308,10 +308,10 @@ Schema.prototype.post = function(type, fn){ * @param {String} name * @param {Function} fn */ -Schema.prototype.method = function(name, fn){ +Schema.prototype.method = function(name, fn) { if (!name) throw new TypeError('Method name is required!'); - if (typeof fn !== 'function'){ + if (typeof fn !== 'function') { throw new TypeError('Instance method must be a function!'); } @@ -325,10 +325,10 @@ Schema.prototype.method = function(name, fn){ * @param {String} name * @param {Function} fn */ -Schema.prototype.static = function(name, fn){ +Schema.prototype.static = function(name, fn) { if (!name) throw new TypeError('Method name is required!'); - if (typeof fn !== 'function'){ + if (typeof fn !== 'function') { throw new TypeError('Static method must be a function!'); } @@ -343,11 +343,11 @@ Schema.prototype.static = function(name, fn){ * @return {*} * @private */ -Schema.prototype._applyGetters = function(data){ +Schema.prototype._applyGetters = function(data) { var stack = this.stacks.getter; var err; - for (var i = 0, len = stack.length; i < len; i++){ + for (var i = 0, len = stack.length; i < len; i++) { err = stack[i](data); if (err instanceof Error) return err; } @@ -361,11 +361,11 @@ Schema.prototype._applyGetters = function(data){ * @return {*} * @private */ -Schema.prototype._applySetters = function(data){ +Schema.prototype._applySetters = function(data) { var stack = this.stacks.setter; var err; - for (var i = 0, len = stack.length; i < len; i++){ + for (var i = 0, len = stack.length; i < len; i++) { err = stack[i](data); if (err instanceof Error) throw err; } @@ -379,11 +379,11 @@ Schema.prototype._applySetters = function(data){ * @return {Object} * @private */ -Schema.prototype._parseDatabase = function(data){ +Schema.prototype._parseDatabase = function(data) { var stack = this.stacks.import; var err; - for (var i = 0, len = stack.length; i < len; i++){ + for (var i = 0, len = stack.length; i < len; i++) { err = stack[i](data); if (err instanceof Error) throw err; } @@ -399,11 +399,11 @@ Schema.prototype._parseDatabase = function(data){ * @return {Object} * @private */ -Schema.prototype._exportDatabase = function(data){ +Schema.prototype._exportDatabase = function(data) { var stack = this.stacks.export; var err; - for (var i = 0, len = stack.length; i < len; i++){ + for (var i = 0, len = stack.length; i < len; i++) { err = stack[i](data); if (err instanceof Error) return err; } @@ -411,16 +411,16 @@ Schema.prototype._exportDatabase = function(data){ return data; }; -function updateStackNormal(key, update){ - return function(data){ +function updateStackNormal(key, update) { + return function(data) { setProp(data, key, update); }; } -function updateStackOperator(path_, ukey, key, update){ +function updateStackOperator(path_, ukey, key, update) { var path = path_ || new SchemaType(key); - return function(data){ + return function(data) { var result = path[ukey](getProp(data, key), update, data); if (result instanceof Error) return result; @@ -437,41 +437,41 @@ function updateStackOperator(path_, ukey, key, update){ * @return {Array} * @private */ -Schema.prototype._parseUpdate = function(updates, prefix_){ +Schema.prototype._parseUpdate = function(updates, prefix_) { var prefix = prefix_ || ''; var paths = this.paths; var stack = []; var keys = Object.keys(updates); var key, update, ukey, name, path, fields, field, j, fieldLen, prefixNoDot; - if (prefix){ + if (prefix) { prefixNoDot = prefix.substring(0, prefix.length - 1); path = paths[prefixNoDot]; } - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; update = updates[key]; name = prefix + key; // Update operators - if (key[0] === '$'){ + if (key[0] === '$') { ukey = 'u' + key; // First-class update operators - if (prefix){ + if (prefix) { stack.push(updateStackOperator(path, ukey, prefixNoDot, update)); } else { // Inline update operators fields = Object.keys(update); fieldLen = fields.length; - for (j = 0; j < fieldLen; j++){ + for (j = 0; j < fieldLen; j++) { field = fields[i]; stack.push( - updateStackOperator(paths[field],ukey, field, update[field])); + updateStackOperator(paths[field], ukey, field, update[field])); } } - } else if (update.constructor === Object){ // Literal objects + } else if (update.constructor === Object) { // Literal objects stack = stack.concat(this._parseUpdate(update, name + '.')); } else { stack.push(updateStackNormal(name, update)); @@ -481,28 +481,28 @@ Schema.prototype._parseUpdate = function(updates, prefix_){ return stack; }; -function queryStackNormal(path_, key, query){ +function queryStackNormal(path_, key, query) { var path = path_ || new SchemaType(key); - return function(data){ + return function(data) { return path.match(getProp(data, key), query, data); }; } -function queryStackOperator(path_, qkey, key, query){ +function queryStackOperator(path_, qkey, key, query) { var path = path_ || new SchemaType(key); - return function(data){ + return function(data) { return path[qkey](getProp(data, key), query, data); }; } -function execQueryStack(stack){ +function execQueryStack(stack) { var len = stack.length; var i; - return function(data){ - for (i = 0; i < len; i++){ + return function(data) { + for (i = 0; i < len; i++) { if (!stack[i](data)) return false; } @@ -510,12 +510,12 @@ function execQueryStack(stack){ }; } -function $or(stack){ +function $or(stack) { var len = stack.length; var i; - return function(data){ - for (i = 0; i < len; i++){ + return function(data) { + for (i = 0; i < len; i++) { if (stack[i](data)) return true; } @@ -523,12 +523,12 @@ function $or(stack){ }; } -function $nor(stack){ +function $nor(stack) { var len = stack.length; var i; - return function(data){ - for (i = 0; i < len; i++){ + return function(data) { + for (i = 0; i < len; i++) { if (stack[i](data)) return false; } @@ -536,16 +536,16 @@ function $nor(stack){ }; } -function $not(stack){ +function $not(stack) { var fn = execQueryStack(stack); - return function(data){ + return function(data) { return !fn(data); }; } -function $where(fn){ - return function(data){ +function $where(fn) { + return function(data) { return fn.call(data); }; } @@ -558,10 +558,10 @@ function $where(fn){ * @return {Array} * @private */ -Schema.prototype._parseQueryArray = function(arr){ +Schema.prototype._parseQueryArray = function(arr) { var stack = []; - for (var i = 0, len = arr.length; i < len; i++){ + for (var i = 0, len = arr.length; i < len; i++) { stack.push(execQueryStack(this._parseQuery(arr[i]))); } @@ -577,26 +577,26 @@ Schema.prototype._parseQueryArray = function(arr){ * @return {Array} * @private */ -Schema.prototype._parseNormalQuery = function(queries, prefix_){ +Schema.prototype._parseNormalQuery = function(queries, prefix_) { var prefix = prefix_ || ''; var paths = this.paths; var stack = []; var keys = Object.keys(queries); var key, query, name, path, prefixNoDot; - if (prefix){ + if (prefix) { prefixNoDot = prefix.substring(0, prefix.length - 1); path = paths[prefixNoDot]; } - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; query = queries[key]; name = prefix + key; - if (key[0] === '$'){ + if (key[0] === '$') { stack.push(queryStackOperator(path, 'q' + key, prefixNoDot, query)); - } else if (query.constructor === Object){ + } else if (query.constructor === Object) { stack = stack.concat(this._parseNormalQuery(query, name + '.')); } else { stack.push(queryStackNormal(paths[name], name, query)); @@ -614,13 +614,13 @@ Schema.prototype._parseNormalQuery = function(queries, prefix_){ * @return {Array} * @private */ -Schema.prototype._parseQuery = function(queries){ +Schema.prototype._parseQuery = function(queries) { var stack = []; var paths = this.paths; var keys = Object.keys(queries); var key, query; - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; query = queries[key]; @@ -646,7 +646,7 @@ Schema.prototype._parseQuery = function(queries){ break; default: - if (query.constructor === Object){ // Literal object + if (query.constructor === Object) { // Literal object stack = stack.concat(this._parseNormalQuery(query, key + '.')); } else { stack.push(queryStackNormal(paths[key], key, query)); @@ -665,19 +665,19 @@ Schema.prototype._parseQuery = function(queries){ * @return {Function} * @private */ -Schema.prototype._execQuery = function(query){ +Schema.prototype._execQuery = function(query) { var stack = this._parseQuery(query); return execQueryStack(stack); }; -function execSortStack(stack){ +function execSortStack(stack) { var len = stack.length; var i; - return function(a, b){ + return function(a, b) { var result; - for (i = 0; i < len; i++){ + for (i = 0; i < len; i++) { result = stack[i](a, b); if (result) break; } @@ -686,11 +686,11 @@ function execSortStack(stack){ }; } -function sortStack(path_, key, sort){ +function sortStack(path_, key, sort) { var path = path_ || new SchemaType(key); var descending = sort === 'desc' || sort === -1; - return function(a, b){ + return function(a, b) { var result = path.compare(getProp(a, key), getProp(b, key)); return descending && result ? result * -1 : result; }; @@ -705,19 +705,19 @@ function sortStack(path_, key, sort){ * @return {Array} * @private */ -Schema.prototype._parseSort = function(sorts, prefix_){ +Schema.prototype._parseSort = function(sorts, prefix_) { var prefix = prefix_ || ''; var paths = this.paths; var stack = []; var keys = Object.keys(sorts); var key, sort, name; - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; sort = sorts[key]; name = prefix + key; - if (typeof sort === 'object'){ + if (typeof sort === 'object') { stack = stack.concat(this._parseSort(sort, name + '.')); } else { stack.push(sortStack(paths[name], name, sort)); @@ -735,7 +735,7 @@ Schema.prototype._parseSort = function(sorts, prefix_){ * @return {Function} * @private */ -Schema.prototype._execSort = function(sorts){ +Schema.prototype._execSort = function(sorts) { var stack = this._parseSort(sorts); return execSortStack(stack); }; @@ -748,24 +748,24 @@ Schema.prototype._execSort = function(sorts){ * @return {Array} * @private */ -Schema.prototype._parsePopulate = function(expr){ +Schema.prototype._parsePopulate = function(expr) { var paths = this.paths; var arr, i, len, item, path, key, ref; - if (typeof expr === 'string'){ + if (typeof expr === 'string') { var split = expr.split(' '); arr = []; - for (i = 0, len = split.length; i < len; i++){ + for (i = 0, len = split.length; i < len; i++) { arr.push({ path: split[i] }); } - } else if (isArray(expr)){ - for (i = 0, len = expr.length; i < len; i++){ + } else if (isArray(expr)) { + for (i = 0, len = expr.length; i < len; i++) { item = expr[i]; - if (typeof item === 'string'){ + if (typeof item === 'string') { arr.push({ path: item }); @@ -777,19 +777,19 @@ Schema.prototype._parsePopulate = function(expr){ arr = [expr]; } - for (i = 0, len = arr.length; i < len; i++){ + for (i = 0, len = arr.length; i < len; i++) { item = arr[i]; key = item.path; - if (!key){ + if (!key) { throw new PopulationError('path is required'); } - if (!item.model){ + if (!item.model) { path = paths[key]; ref = path.child ? path.child.options.ref : path.options.ref; - if (ref){ + if (ref) { item.model = ref; } else { throw new PopulationError('model is required'); @@ -806,4 +806,4 @@ Schema.prototype._parsePopulate = function(expr){ */ Schema.Types = Schema.prototype.Types = Types; -module.exports = Schema; \ No newline at end of file +module.exports = Schema; diff --git a/lib/schematype.js b/lib/schematype.js index 092de8e0..f97c93f6 100644 --- a/lib/schematype.js +++ b/lib/schematype.js @@ -62,7 +62,7 @@ var extend = util.extend; * @constructor * @module warehouse */ -function SchemaType(name, options){ +function SchemaType(name, options) { /** * Field name. * @@ -86,10 +86,10 @@ function SchemaType(name, options){ * * @property {Function} default */ - if (typeof default_ === 'function'){ + if (typeof default_ === 'function') { this.default = default_; } else { - this.default = function(){ + this.default = function() { return default_; }; } @@ -104,12 +104,12 @@ function SchemaType(name, options){ * @param {Object} data * @return {*} */ -SchemaType.prototype.cast = function(value, data){ - if (value == null){ +SchemaType.prototype.cast = function(value, data) { + if (value == null) { return this.default(); - } else { - return value; } + + return value; }; /** @@ -120,8 +120,8 @@ SchemaType.prototype.cast = function(value, data){ * @param {Object} data * @return {*|Error} */ -SchemaType.prototype.validate = function(value, data){ - if (this.options.required && value == null){ +SchemaType.prototype.validate = function(value, data) { + if (this.options.required && value == null) { return new ValidationError('`' + this.name + '` is required!'); } @@ -136,14 +136,14 @@ SchemaType.prototype.validate = function(value, data){ * @param {*} b * @return {Number} */ -SchemaType.prototype.compare = function(a, b){ - if (a > b){ +SchemaType.prototype.compare = function(a, b) { + if (a > b) { return 1; - } else if (a < b){ + } else if (a < b) { return -1; - } else { - return 0; } + + return 0; }; /** @@ -154,7 +154,7 @@ SchemaType.prototype.compare = function(a, b){ * @param {Object} data * @return {*} */ -SchemaType.prototype.parse = function(value, data){ +SchemaType.prototype.parse = function(value, data) { return value; }; @@ -166,7 +166,7 @@ SchemaType.prototype.parse = function(value, data){ * @param {Object} data * @return {*} */ -SchemaType.prototype.value = function(value, data){ +SchemaType.prototype.value = function(value, data) { return value; }; @@ -179,7 +179,7 @@ SchemaType.prototype.value = function(value, data){ * @param {Object} data * @return {Boolean} */ -SchemaType.prototype.match = function(value, query, data){ +SchemaType.prototype.match = function(value, query, data) { return value === query; }; @@ -192,8 +192,8 @@ SchemaType.prototype.match = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaType.prototype.q$exist = function(value, query, data){ - return (value != null) == query; +SchemaType.prototype.q$exist = function(value, query, data) { + return (value != null) === query; }; /** @@ -212,7 +212,7 @@ SchemaType.prototype.q$exists = SchemaType.prototype.q$exist; * @param {Object} data * @return {boolean} */ -SchemaType.prototype.q$ne = function(value, query, data){ +SchemaType.prototype.q$ne = function(value, query, data) { return !this.match(value, query, data); }; @@ -225,7 +225,7 @@ SchemaType.prototype.q$ne = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaType.prototype.q$lt = function(value, query, data){ +SchemaType.prototype.q$lt = function(value, query, data) { return value < query; }; @@ -238,7 +238,7 @@ SchemaType.prototype.q$lt = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaType.prototype.q$lte = function(value, query, data){ +SchemaType.prototype.q$lte = function(value, query, data) { return value <= query; }; @@ -258,7 +258,7 @@ SchemaType.prototype.q$max = SchemaType.prototype.q$lte; * @param {Object} data * @return {Boolean} */ -SchemaType.prototype.q$gt = function(value, query, data){ +SchemaType.prototype.q$gt = function(value, query, data) { return value > query; }; @@ -271,7 +271,7 @@ SchemaType.prototype.q$gt = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaType.prototype.q$gte = function(value, query, data){ +SchemaType.prototype.q$gte = function(value, query, data) { return value >= query; }; @@ -291,7 +291,7 @@ SchemaType.prototype.q$min = SchemaType.prototype.q$gte; * @param {Object} data * @return {Boolean} */ -SchemaType.prototype.q$in = function(value, query, data){ +SchemaType.prototype.q$in = function(value, query, data) { return contains(query, value); }; @@ -304,7 +304,7 @@ SchemaType.prototype.q$in = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaType.prototype.q$nin = function(value, query, data){ +SchemaType.prototype.q$nin = function(value, query, data) { return !contains(query, value); }; @@ -317,7 +317,7 @@ SchemaType.prototype.q$nin = function(value, query, data){ * @param {Object} data * @return {*} */ -SchemaType.prototype.u$set = function(value, update, data){ +SchemaType.prototype.u$set = function(value, update, data) { return update; }; @@ -330,7 +330,7 @@ SchemaType.prototype.u$set = function(value, update, data){ * @param {Object} data * @return {*} */ -SchemaType.prototype.u$unset = function(value, update, data){ +SchemaType.prototype.u$unset = function(value, update, data) { return update ? undefined : value; }; @@ -343,9 +343,9 @@ SchemaType.prototype.u$unset = function(value, update, data){ * @param {Object} data * @return {*} */ -SchemaType.prototype.u$rename = function(value, update, data){ +SchemaType.prototype.u$rename = function(value, update, data) { if (value !== undefined) setProp(data, update, value); return undefined; }; -module.exports = SchemaType; \ No newline at end of file +module.exports = SchemaType; diff --git a/lib/types/array.js b/lib/types/array.js index 6706e4e3..5c7df5ba 100644 --- a/lib/types/array.js +++ b/lib/types/array.js @@ -22,7 +22,7 @@ var isArray = Array.isArray; * @extends {SchemaType} * @module warehouse */ -function SchemaTypeArray(name, options){ +function SchemaTypeArray(name, options) { SchemaType.call(this, name, extend({ default: [] }, options)); @@ -45,7 +45,7 @@ util.inherits(SchemaTypeArray, SchemaType); * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.cast = function(value_, data){ +SchemaTypeArray.prototype.cast = function(value_, data) { var value = SchemaType.prototype.cast.call(this, value_, data); if (value == null) return value; @@ -54,7 +54,7 @@ SchemaTypeArray.prototype.cast = function(value_, data){ var child = this.child; - for (var i = 0, len = value.length; i < len; i++){ + for (var i = 0, len = value.length; i < len; i++) { value[i] = child.cast(value[i], data); } @@ -69,11 +69,11 @@ SchemaTypeArray.prototype.cast = function(value_, data){ * @param {Object} data * @return {Array|Error} */ -SchemaTypeArray.prototype.validate = function(value_, data){ +SchemaTypeArray.prototype.validate = function(value_, data) { var value = SchemaType.prototype.validate.call(this, value_, data); if (value instanceof Error) return value; - if (!isArray(value)){ + if (!isArray(value)) { return new ValidationError('`' + value + '` is not an array!'); } @@ -82,14 +82,14 @@ SchemaTypeArray.prototype.validate = function(value_, data){ var child = this.child; var result; - for (var i = 0, len = value.length; i < len; i++){ + for (var i = 0, len = value.length; i < len; i++) { result = child.validate(value[i], data); - if (result instanceof Error){ + if (result instanceof Error) { return result; - } else { - value[i] = result; } + + value[i] = result; } return value; @@ -103,8 +103,8 @@ SchemaTypeArray.prototype.validate = function(value_, data){ * @param {Array} b * @return {Number} */ -SchemaTypeArray.prototype.compare = function(a, b){ - if (a){ +SchemaTypeArray.prototype.compare = function(a, b) { + if (a) { if (!b) return 1; } else { return b ? -1 : 0; @@ -115,7 +115,7 @@ SchemaTypeArray.prototype.compare = function(a, b){ var child = this.child; var result; - for (var i = 0, len = Math.min(lenA, lenB); i < len; i++){ + for (var i = 0, len = Math.min(lenA, lenB); i < len; i++) { result = child.compare(a[i], b[i]); if (result !== 0) return result; } @@ -132,7 +132,7 @@ SchemaTypeArray.prototype.compare = function(a, b){ * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.parse = function(value, data){ +SchemaTypeArray.prototype.parse = function(value, data) { if (!value) return value; var len = value.length; @@ -141,7 +141,7 @@ SchemaTypeArray.prototype.parse = function(value, data){ var result = new Array(len); var child = this.child; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { result[i] = child.parse(value[i], data); } @@ -156,7 +156,7 @@ SchemaTypeArray.prototype.parse = function(value, data){ * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.value = function(value, data){ +SchemaTypeArray.prototype.value = function(value, data) { if (!value) return value; var len = value.length; @@ -165,7 +165,7 @@ SchemaTypeArray.prototype.value = function(value, data){ var result = new Array(len); var child = this.child; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { result[i] = child.value(value[i], data); } @@ -181,7 +181,7 @@ SchemaTypeArray.prototype.value = function(value, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeArray.prototype.match = function(value, query, data){ +SchemaTypeArray.prototype.match = function(value, query, data) { if (!value) return false; var lenA = value.length; @@ -191,7 +191,7 @@ SchemaTypeArray.prototype.match = function(value, query, data){ var child = this.child; - for (var i = 0; i < lenA; i++){ + for (var i = 0; i < lenA; i++) { if (!child.match(value[i], query[i], data)) return false; } @@ -207,7 +207,7 @@ SchemaTypeArray.prototype.match = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeArray.prototype.q$size = function(value, query, data){ +SchemaTypeArray.prototype.q$size = function(value, query, data) { return (value ? value.length : 0) === query; }; @@ -227,10 +227,10 @@ SchemaTypeArray.prototype.q$length = SchemaTypeArray.prototype.q$size; * @param {Object} data * @return {Boolean} */ -SchemaTypeArray.prototype.q$in = function(value, query, data){ +SchemaTypeArray.prototype.q$in = function(value, query, data) { if (!value) return false; - for (var i = 0, len = query.length; i < len; i++){ + for (var i = 0, len = query.length; i < len; i++) { if (contains(value, query[i])) return true; } @@ -246,10 +246,10 @@ SchemaTypeArray.prototype.q$in = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeArray.prototype.q$nin = function(value, query, data){ +SchemaTypeArray.prototype.q$nin = function(value, query, data) { if (!value) return true; - for (var i = 0, len = query.length; i < len; i++){ + for (var i = 0, len = query.length; i < len; i++) { if (contains(value, query[i])) return false; } @@ -265,10 +265,10 @@ SchemaTypeArray.prototype.q$nin = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeArray.prototype.q$all = function(value, query, data){ +SchemaTypeArray.prototype.q$all = function(value, query, data) { if (!value) return false; - for (var i = 0, len = query.length; i < len; i++){ + for (var i = 0, len = query.length; i < len; i++) { if (!contains(value, query[i])) return false; } @@ -284,17 +284,17 @@ SchemaTypeArray.prototype.q$all = function(value, query, data){ * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.u$push = function(value, update, data){ - if (isArray(update)){ +SchemaTypeArray.prototype.u$push = function(value, update, data) { + if (isArray(update)) { return value ? value.concat(update) : update; - } else { - if (value){ - value.push(update); - return value; - } else { - return [update]; - } } + + if (value) { + value.push(update); + return value; + } + + return [update]; }; /** @@ -313,17 +313,17 @@ SchemaTypeArray.prototype.u$append = SchemaTypeArray.prototype.u$push; * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.u$unshift = function(value, update, data){ - if (isArray(update)){ +SchemaTypeArray.prototype.u$unshift = function(value, update, data) { + if (isArray(update)) { return value ? update.concat(value) : update; - } else { - if (value){ - value.unshift(update); - return value; - } else { - return [update]; - } } + + if (value) { + value.unshift(update); + return value; + } + + return [update]; }; /** @@ -342,14 +342,14 @@ SchemaTypeArray.prototype.u$prepend = SchemaTypeArray.prototype.u$unshift; * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.u$pull = function(value, update, data){ +SchemaTypeArray.prototype.u$pull = function(value, update, data) { if (!value) return value; - if (isArray(update)){ + if (isArray(update)) { return _.difference(value, update); - } else { - return _.without(value, update); } + + return _.without(value, update); }; /** @@ -361,16 +361,16 @@ SchemaTypeArray.prototype.u$pull = function(value, update, data){ * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.u$shift = function(value, update, data){ +SchemaTypeArray.prototype.u$shift = function(value, update, data) { if (!value || !update) return value; - if (update === true){ + if (update === true) { return value.slice(1); - } else if (update > 0){ + } else if (update > 0) { return value.slice(update); - } else { - return value.slice(0, value.length + update); } + + return value.slice(0, value.length + update); }; /** @@ -382,18 +382,18 @@ SchemaTypeArray.prototype.u$shift = function(value, update, data){ * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.u$pop = function(value, update, data){ +SchemaTypeArray.prototype.u$pop = function(value, update, data) { if (!value || !update) return value; var length = value.length; - if (update === true){ + if (update === true) { return value.slice(0, length - 1); - } else if (update > 0){ + } else if (update > 0) { return value.slice(0, length - update); - } else { - return value.slice(-update, length); } + + return value.slice(-update, length); }; /** @@ -405,27 +405,27 @@ SchemaTypeArray.prototype.u$pop = function(value, update, data){ * @param {Object} data * @return {Array} */ -SchemaTypeArray.prototype.u$addToSet = function(value, update, data){ - if (isArray(update)){ +SchemaTypeArray.prototype.u$addToSet = function(value, update, data) { + if (isArray(update)) { if (!value) return update; var item; - for (var i = 0, len = update.length; i < len; i++){ + for (var i = 0, len = update.length; i < len; i++) { item = update[i]; if (!contains(value, item)) value.push(item); } return value; - } else { - if (!value) return [update]; + } - if (!contains(value, update)){ - value.push(update); - } + if (!value) return [update]; - return value; + if (!contains(value, update)) { + value.push(update); } + + return value; }; -module.exports = SchemaTypeArray; \ No newline at end of file +module.exports = SchemaTypeArray; diff --git a/lib/types/boolean.js b/lib/types/boolean.js index 6fd76c9a..482214c8 100644 --- a/lib/types/boolean.js +++ b/lib/types/boolean.js @@ -16,7 +16,7 @@ var ValidationError = require('../error/validation'); * @extends {SchemaType} * @module warehouse */ -function SchemaTypeBoolean(name, options){ +function SchemaTypeBoolean(name, options) { SchemaType.call(this, name, options); } @@ -30,7 +30,7 @@ util.inherits(SchemaTypeBoolean, SchemaType); * @param {Object} data * @return {Boolean} */ -SchemaTypeBoolean.prototype.cast = function(value_, data){ +SchemaTypeBoolean.prototype.cast = function(value_, data) { var value = SchemaType.prototype.cast.call(this, value_, data); if (value === 'false' || value === '0') return false; @@ -46,11 +46,11 @@ SchemaTypeBoolean.prototype.cast = function(value_, data){ * @param {Object} data * @return {Boolean|Error} */ -SchemaTypeBoolean.prototype.validate = function(value_, data){ +SchemaTypeBoolean.prototype.validate = function(value_, data) { var value = SchemaType.prototype.validate.call(this, value_, data); if (value instanceof Error) return value; - if (value != null && typeof value !== 'boolean'){ + if (value != null && typeof value !== 'boolean') { return new ValidationError('`' + value + '` is not a boolean!'); } @@ -65,7 +65,7 @@ SchemaTypeBoolean.prototype.validate = function(value_, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeBoolean.prototype.parse = function(value, data){ +SchemaTypeBoolean.prototype.parse = function(value, data) { return Boolean(value); }; @@ -77,8 +77,8 @@ SchemaTypeBoolean.prototype.parse = function(value, data){ * @param {Object} data * @return {Number} */ -SchemaTypeBoolean.prototype.value = function(value, data){ +SchemaTypeBoolean.prototype.value = function(value, data) { return +value; }; -module.exports = SchemaTypeBoolean; \ No newline at end of file +module.exports = SchemaTypeBoolean; diff --git a/lib/types/cuid.js b/lib/types/cuid.js index 014b93ba..45ef0051 100644 --- a/lib/types/cuid.js +++ b/lib/types/cuid.js @@ -16,7 +16,7 @@ var ValidationError = require('../error/validation'); * @extends {SchemaType} * @module warehouse */ -function SchemaTypeCUID(name, options){ +function SchemaTypeCUID(name, options) { SchemaType.call(this, name, options); } @@ -31,12 +31,12 @@ util.inherits(SchemaTypeCUID, SchemaType); * @param {Object} data * @return {String} */ -SchemaTypeCUID.prototype.cast = function(value, data){ - if (value == null && this.options.required){ +SchemaTypeCUID.prototype.cast = function(value, data) { + if (value == null && this.options.required) { return cuid(); - } else { - return value; } + + return value; }; /** @@ -47,12 +47,12 @@ SchemaTypeCUID.prototype.cast = function(value, data){ * @param {Object} data * @return {String|Error} */ -SchemaTypeCUID.prototype.validate = function(value, data){ - if (value && (value[0] !== 'c' || value.length !== 25)){ +SchemaTypeCUID.prototype.validate = function(value, data) { + if (value && (value[0] !== 'c' || value.length !== 25)) { return new ValidationError('`' + value + '` is not a valid CUID'); } return value; }; -module.exports = SchemaTypeCUID; \ No newline at end of file +module.exports = SchemaTypeCUID; diff --git a/lib/types/date.js b/lib/types/date.js index 2050ccbf..c53ff63d 100644 --- a/lib/types/date.js +++ b/lib/types/date.js @@ -16,7 +16,7 @@ var ValidationError = require('../error/validation'); * @extends {SchemaType} * @module warehouse */ -function SchemaTypeDate(name, options){ +function SchemaTypeDate(name, options) { SchemaType.call(this, name, options); } @@ -30,7 +30,7 @@ util.inherits(SchemaTypeDate, SchemaType); * @param {Object} data * @return {Date} */ -SchemaTypeDate.prototype.cast = function(value_, data){ +SchemaTypeDate.prototype.cast = function(value_, data) { var value = SchemaType.prototype.cast.call(this, value_, data); if (value == null || util.isDate(value)) return value; @@ -46,11 +46,11 @@ SchemaTypeDate.prototype.cast = function(value_, data){ * @param {Object} data * @return {Date|Error} */ -SchemaTypeDate.prototype.validate = function(value_, data){ +SchemaTypeDate.prototype.validate = function(value_, data) { var value = SchemaType.prototype.validate.call(this, value_, data); if (value instanceof Error) return value; - if (value != null && (!util.isDate(value) || isNaN(value.getTime())) ){ + if (value != null && (!util.isDate(value) || isNaN(value.getTime()))) { return new ValidationError('`' + value + '` is not a valid date!'); } @@ -66,7 +66,7 @@ SchemaTypeDate.prototype.validate = function(value_, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeDate.prototype.match = function(value, query, data){ +SchemaTypeDate.prototype.match = function(value, query, data) { return value ? value.getTime() === query.getTime() : false; }; @@ -78,20 +78,12 @@ SchemaTypeDate.prototype.match = function(value, query, data){ * @param {Date} b * @return {Number} */ -SchemaTypeDate.prototype.compare = function(a, b){ - if (a){ - if (b){ // a && b - return a - b; - } else { // a && !b - return 1; - } - } else { - if (b){ // !a && b - return -1; - } else { // !a && !b - return 0; - } +SchemaTypeDate.prototype.compare = function(a, b) { + if (a) { + return b ? a - b : 1; } + + return b ? -1 : 0; }; /** @@ -102,7 +94,7 @@ SchemaTypeDate.prototype.compare = function(a, b){ * @param {Object} data * @return {Date} */ -SchemaTypeDate.prototype.parse = function(value, data){ +SchemaTypeDate.prototype.parse = function(value, data) { if (value) return new Date(value); }; @@ -114,7 +106,7 @@ SchemaTypeDate.prototype.parse = function(value, data){ * @param {Object} data * @return {String} */ -SchemaTypeDate.prototype.value = function(value, data){ +SchemaTypeDate.prototype.value = function(value, data) { return value ? value.toISOString() : value; }; @@ -127,7 +119,7 @@ SchemaTypeDate.prototype.value = function(value, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeDate.prototype.q$day = function(value, query, data){ +SchemaTypeDate.prototype.q$day = function(value, query, data) { return value ? value.getDate() === query : false; }; @@ -140,7 +132,7 @@ SchemaTypeDate.prototype.q$day = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeDate.prototype.q$month = function(value, query, data){ +SchemaTypeDate.prototype.q$month = function(value, query, data) { return value ? value.getMonth() === query : false; }; @@ -153,7 +145,7 @@ SchemaTypeDate.prototype.q$month = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeDate.prototype.q$year = function(value, query, data){ +SchemaTypeDate.prototype.q$year = function(value, query, data) { return value ? value.getFullYear() === query : false; }; @@ -166,7 +158,7 @@ SchemaTypeDate.prototype.q$year = function(value, query, data){ * @param {Object} data * @return {Date} */ -SchemaTypeDate.prototype.u$inc = function(value, update, data){ +SchemaTypeDate.prototype.u$inc = function(value, update, data) { if (value) return new Date(value.getTime() + update); }; @@ -179,8 +171,8 @@ SchemaTypeDate.prototype.u$inc = function(value, update, data){ * @param {Object} data * @return {Date} */ -SchemaTypeDate.prototype.u$dec = function(value, update, data){ +SchemaTypeDate.prototype.u$dec = function(value, update, data) { if (value) return new Date(value.getTime() - update); }; -module.exports = SchemaTypeDate; \ No newline at end of file +module.exports = SchemaTypeDate; diff --git a/lib/types/enum.js b/lib/types/enum.js index fd5fa56b..66ba51e6 100644 --- a/lib/types/enum.js +++ b/lib/types/enum.js @@ -19,7 +19,7 @@ var extend = util.extend; * @extends {SchemaType} * @module warehouse */ -function SchemaTypeEnum(name, options){ +function SchemaTypeEnum(name, options) { SchemaType.call(this, name, extend({ elements: [] }, options)); @@ -35,17 +35,17 @@ util.inherits(SchemaTypeEnum, SchemaType); * @param {Object} data * @return {*} */ -SchemaTypeEnum.prototype.validate = function(value_, data){ +SchemaTypeEnum.prototype.validate = function(value_, data) { var value = SchemaType.prototype.validate.call(this, value_, data); if (value instanceof Error) return value; var elements = this.options.elements; - if (!util.contains(elements, value)){ + if (!util.contains(elements, value)) { return new ValidationError('The value must be one of ' + elements.join(', ')); } return value; }; -module.exports = SchemaTypeEnum; \ No newline at end of file +module.exports = SchemaTypeEnum; diff --git a/lib/types/index.js b/lib/types/index.js index c45472a9..50f00318 100644 --- a/lib/types/index.js +++ b/lib/types/index.js @@ -1,3 +1,5 @@ +'use strict'; + exports.Mixed = require('../schematype'); exports.String = require('./string'); exports.Number = require('./number'); @@ -8,4 +10,4 @@ exports.Date = require('./date'); exports.Virtual = require('./virtual'); exports.CUID = require('./cuid'); exports.Enum = require('./enum'); -exports.Integer = require('./integer'); \ No newline at end of file +exports.Integer = require('./integer'); diff --git a/lib/types/integer.js b/lib/types/integer.js index 45431963..ef66035f 100644 --- a/lib/types/integer.js +++ b/lib/types/integer.js @@ -16,7 +16,7 @@ var ValidationError = require('../error/validation'); * @extends {SchemaTypeNumber} * @module warehouse */ -function SchemaTypeInteger(name, options){ +function SchemaTypeInteger(name, options) { SchemaTypeNumber.call(this, name, options); } @@ -30,7 +30,7 @@ util.inherits(SchemaTypeInteger, SchemaTypeNumber); * @param {Object} data * @return {Number} */ -SchemaTypeInteger.prototype.cast = function(value_, data){ +SchemaTypeInteger.prototype.cast = function(value_, data) { var value = SchemaTypeNumber.prototype.cast.call(this, value_, data); return parseInt(value, 10); @@ -44,15 +44,15 @@ SchemaTypeInteger.prototype.cast = function(value_, data){ * @param {Object} data * @return {Number|Error} */ -SchemaTypeInteger.prototype.validate = function(value_, data){ +SchemaTypeInteger.prototype.validate = function(value_, data) { var value = SchemaTypeNumber.prototype.validate.call(this, value_, data); if (value instanceof Error) return value; - if (value % 1 !== 0){ + if (value % 1 !== 0) { return new ValidationError('`' + value + '` is not an integer!'); } return value; }; -module.exports = SchemaTypeInteger; \ No newline at end of file +module.exports = SchemaTypeInteger; diff --git a/lib/types/number.js b/lib/types/number.js index 0d6938c9..d8725ffc 100644 --- a/lib/types/number.js +++ b/lib/types/number.js @@ -16,7 +16,7 @@ var ValidationError = require('../error/validation'); * @extends {SchemaType} * @module warehouse */ -function SchemaTypeNumber(name, options){ +function SchemaTypeNumber(name, options) { SchemaType.call(this, name, options); } @@ -30,7 +30,7 @@ util.inherits(SchemaTypeNumber, SchemaType); * @param {Object} data * @return {Number} */ -SchemaTypeNumber.prototype.cast = function(value_, data){ +SchemaTypeNumber.prototype.cast = function(value_, data) { var value = SchemaType.prototype.cast.call(this, value_, data); if (value == null || typeof value === 'number') return value; @@ -46,11 +46,11 @@ SchemaTypeNumber.prototype.cast = function(value_, data){ * @param {Object} data * @return {Number|Error} */ -SchemaTypeNumber.prototype.validate = function(value_, data){ +SchemaTypeNumber.prototype.validate = function(value_, data) { var value = SchemaType.prototype.validate.call(this, value_, data); if (value instanceof Error) return value; - if (value !== undefined && (typeof value !== 'number' || isNaN(value))){ + if (value !== undefined && (typeof value !== 'number' || isNaN(value))) { return new ValidationError('`' + value + '` is not a number!'); } @@ -66,7 +66,7 @@ SchemaTypeNumber.prototype.validate = function(value_, data){ * @param {Object} data * @return {Number} */ -SchemaTypeNumber.prototype.u$inc = function(value, update, data){ +SchemaTypeNumber.prototype.u$inc = function(value, update, data) { return value ? value + update : update; }; @@ -79,7 +79,7 @@ SchemaTypeNumber.prototype.u$inc = function(value, update, data){ * @param {Object} data * @return {Number} */ -SchemaTypeNumber.prototype.u$dec = function(value, update, data){ +SchemaTypeNumber.prototype.u$dec = function(value, update, data) { return value ? value - update : -update; }; @@ -92,7 +92,7 @@ SchemaTypeNumber.prototype.u$dec = function(value, update, data){ * @param {Object} data * @return {Number} */ -SchemaTypeNumber.prototype.u$mul = function(value, update, data){ +SchemaTypeNumber.prototype.u$mul = function(value, update, data) { return value ? value * update : 0; }; @@ -105,7 +105,7 @@ SchemaTypeNumber.prototype.u$mul = function(value, update, data){ * @param {Object} data * @return {Number} */ -SchemaTypeNumber.prototype.u$div = function(value, update, data){ +SchemaTypeNumber.prototype.u$div = function(value, update, data) { return value ? value / update : 0; }; @@ -118,7 +118,7 @@ SchemaTypeNumber.prototype.u$div = function(value, update, data){ * @param {Object} data * @return {Number} */ -SchemaTypeNumber.prototype.u$mod = function(value, update, data){ +SchemaTypeNumber.prototype.u$mod = function(value, update, data) { return value ? value % update : 0; }; @@ -131,7 +131,7 @@ SchemaTypeNumber.prototype.u$mod = function(value, update, data){ * @param {Object} data * @return {Number} */ -SchemaTypeNumber.prototype.u$max = function(value, update, data){ +SchemaTypeNumber.prototype.u$max = function(value, update, data) { return update > value ? update : value; }; @@ -144,8 +144,8 @@ SchemaTypeNumber.prototype.u$max = function(value, update, data){ * @param {Object} data * @return {Number} */ -SchemaTypeNumber.prototype.u$min = function(value, update, data){ +SchemaTypeNumber.prototype.u$min = function(value, update, data) { return update < value ? update : value; }; -module.exports = SchemaTypeNumber; \ No newline at end of file +module.exports = SchemaTypeNumber; diff --git a/lib/types/object.js b/lib/types/object.js index 85d6a191..c9ec74e6 100644 --- a/lib/types/object.js +++ b/lib/types/object.js @@ -17,7 +17,7 @@ var extend = util.extend; * @extends {SchemaType} * @module warehouse */ -function SchemaTypeObject(name, options){ +function SchemaTypeObject(name, options) { SchemaType.call(this, name, extend({ default: {} }, options)); @@ -25,4 +25,4 @@ function SchemaTypeObject(name, options){ util.inherits(SchemaTypeObject, SchemaType); -module.exports = SchemaTypeObject; \ No newline at end of file +module.exports = SchemaTypeObject; diff --git a/lib/types/string.js b/lib/types/string.js index 412543a7..69a248fa 100644 --- a/lib/types/string.js +++ b/lib/types/string.js @@ -16,7 +16,7 @@ var ValidationError = require('../error/validation'); * @extends {SchemaType} * @module warehouse */ -function SchemaTypeString(name, options){ +function SchemaTypeString(name, options) { SchemaType.call(this, name, options); } @@ -30,7 +30,7 @@ util.inherits(SchemaTypeString, SchemaType); * @param {Object} data * @return {String} */ -SchemaTypeString.prototype.cast = function(value_, data){ +SchemaTypeString.prototype.cast = function(value_, data) { var value = SchemaType.prototype.cast.call(this, value_, data); if (value == null || typeof value === 'string') return value; @@ -45,11 +45,11 @@ SchemaTypeString.prototype.cast = function(value_, data){ * @param {Object} data * @return {String|Error} */ -SchemaTypeString.prototype.validate = function(value_, data){ +SchemaTypeString.prototype.validate = function(value_, data) { var value = SchemaType.prototype.validate.call(this, value_, data); if (value instanceof Error) return value; - if (value !== undefined && typeof value !== 'string'){ + if (value !== undefined && typeof value !== 'string') { return new ValidationError('`' + value + '` is not a string!'); } @@ -65,12 +65,12 @@ SchemaTypeString.prototype.validate = function(value_, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeString.prototype.match = function(value, query, data){ - if (typeof query.test === 'function'){ +SchemaTypeString.prototype.match = function(value, query, data) { + if (typeof query.test === 'function') { return query.test(value); - } else { - return value === query; } + + return value === query; }; /** @@ -82,8 +82,8 @@ SchemaTypeString.prototype.match = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeString.prototype.q$in = function(value, query, data){ - for (var i = 0, len = query.length; i < len; i++){ +SchemaTypeString.prototype.q$in = function(value, query, data) { + for (var i = 0, len = query.length; i < len; i++) { if (this.match(value, query[i], data)) return true; } @@ -99,7 +99,7 @@ SchemaTypeString.prototype.q$in = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeString.prototype.q$nin = function(value, query, data){ +SchemaTypeString.prototype.q$nin = function(value, query, data) { return !this.q$in(value, query, data); }; @@ -112,8 +112,8 @@ SchemaTypeString.prototype.q$nin = function(value, query, data){ * @param {Object} data * @return {Boolean} */ -SchemaTypeString.prototype.q$length = function(value, query, data){ +SchemaTypeString.prototype.q$length = function(value, query, data) { return (value ? value.length : 0) === query; }; -module.exports = SchemaTypeString; \ No newline at end of file +module.exports = SchemaTypeString; diff --git a/lib/types/virtual.js b/lib/types/virtual.js index e8e6fe63..b08f090d 100644 --- a/lib/types/virtual.js +++ b/lib/types/virtual.js @@ -15,7 +15,7 @@ var setGetter = util.setGetter; * @extends {SchemaType} * @module warehouse */ -function SchemaTypeVirtual(name, options){ +function SchemaTypeVirtual(name, options) { SchemaType.call(this, name, options); } @@ -28,8 +28,8 @@ util.inherits(SchemaTypeVirtual, SchemaType); * @param {Function} fn * @chainable */ -SchemaTypeVirtual.prototype.get = function(fn){ - if (typeof fn !== 'function'){ +SchemaTypeVirtual.prototype.get = function(fn) { + if (typeof fn !== 'function') { throw new TypeError('Getter must be a function!'); } @@ -45,8 +45,8 @@ SchemaTypeVirtual.prototype.get = function(fn){ * @param {Function} fn * @chainable */ -SchemaTypeVirtual.prototype.set = function(fn){ - if (typeof fn !== 'function'){ +SchemaTypeVirtual.prototype.set = function(fn) { + if (typeof fn !== 'function') { throw new TypeError('Setter must be a function!'); } @@ -63,15 +63,15 @@ SchemaTypeVirtual.prototype.set = function(fn){ * @param {Object} data * @return {*} */ -SchemaTypeVirtual.prototype.cast = function(value, data){ +SchemaTypeVirtual.prototype.cast = function(value, data) { if (typeof this.getter !== 'function') return; var getter = this.getter; var hasCache = false; var cache; - setGetter(data, this.name, function(){ - if (!hasCache){ + setGetter(data, this.name, function() { + if (!hasCache) { cache = getter.call(data); hasCache = true; } @@ -87,8 +87,8 @@ SchemaTypeVirtual.prototype.cast = function(value, data){ * @param {*} value * @param {Object} data */ -SchemaTypeVirtual.prototype.validate = function(value, data){ - if (typeof this.setter === 'function'){ +SchemaTypeVirtual.prototype.validate = function(value, data) { + if (typeof this.setter === 'function') { this.setter.call(data, value); } }; diff --git a/lib/util.js b/lib/util.js index c39862d0..cdd47aef 100644 --- a/lib/util.js +++ b/lib/util.js @@ -13,7 +13,7 @@ var util = require('util'); exports.inherits = util.inherits; exports.isDate = util.isDate; -function extractPropKey(key){ +function extractPropKey(key) { return key.split('.'); } @@ -26,7 +26,7 @@ function extractPropKey(key){ * @return {*} * @static */ -exports.getProp = function(obj, key){ +exports.getProp = function(obj, key) { if (typeof obj !== 'object') throw new TypeError('obj must be an object!'); if (!key) throw new TypeError('key is required!'); @@ -36,7 +36,7 @@ exports.getProp = function(obj, key){ if (!len) return result; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { result = result[token[i]]; } @@ -52,7 +52,7 @@ exports.getProp = function(obj, key){ * @param {*} value * @static */ -exports.setProp = function(obj, key, value){ +exports.setProp = function(obj, key, value) { if (typeof obj !== 'object') throw new TypeError('obj must be an object!'); if (!key) throw new TypeError('key is required!'); @@ -60,7 +60,7 @@ exports.setProp = function(obj, key, value){ var lastKey = token.pop(); var len = token.length; - if (!len){ + if (!len) { obj[lastKey] = value; return; } @@ -68,7 +68,7 @@ exports.setProp = function(obj, key, value){ var cursor = obj; var name; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { name = token[i]; cursor = cursor[name] = cursor[name] || {}; } @@ -84,7 +84,7 @@ exports.setProp = function(obj, key, value){ * @param {String} key * @static */ -exports.delProp = function(obj, key){ +exports.delProp = function(obj, key) { if (typeof obj !== 'object') throw new TypeError('obj must be an object!'); if (!key) throw new TypeError('key is required!'); @@ -92,7 +92,7 @@ exports.delProp = function(obj, key){ var lastKey = token.pop(); var len = token.length; - if (!len){ + if (!len) { delete obj[lastKey]; return; } @@ -100,10 +100,10 @@ exports.delProp = function(obj, key){ var cursor = obj; var name; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { name = token[i]; - if (cursor[name]){ + if (cursor[name]) { cursor = cursor[name]; } else { return; @@ -121,7 +121,7 @@ exports.delProp = function(obj, key){ * @param {String} key * @param {Function} fn */ -exports.setGetter = function(obj, key, fn){ +exports.setGetter = function(obj, key, fn) { if (typeof obj !== 'object') throw new TypeError('obj must be an object!'); if (!key) throw new TypeError('key is required!'); if (typeof fn !== 'function') throw new TypeError('fn must be a function!'); @@ -130,7 +130,7 @@ exports.setGetter = function(obj, key, fn){ var lastKey = token.pop(); var len = token.length; - if (!len){ + if (!len) { obj.__defineGetter__(lastKey, fn); return; } @@ -138,7 +138,7 @@ exports.setGetter = function(obj, key, fn){ var cursor = obj; var name; - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { name = token[i]; cursor = cursor[name] = cursor[name] || {}; } @@ -155,13 +155,13 @@ exports.setGetter = function(obj, key, fn){ * @return {Object} * @static */ -exports.arr2obj = function(arr, value){ +exports.arr2obj = function(arr, value) { if (!Array.isArray(arr)) throw new TypeError('arr must be an array!'); var obj = {}; var i = arr.length; - while (i--){ + while (i--) { obj[arr[i]] = value; } @@ -177,7 +177,7 @@ exports.arr2obj = function(arr, value){ * @return {Boolean} * @static */ -exports.arrayEqual = function(a, b){ +exports.arrayEqual = function(a, b) { if (!Array.isArray(a)) throw new TypeError('a must be an array!'); if (!Array.isArray(b)) throw new TypeError('b must be an array!'); @@ -185,7 +185,7 @@ exports.arrayEqual = function(a, b){ if (i !== b.length) return false; - while (i--){ + while (i--) { if (a[i] !== b[i]) return false; } @@ -199,13 +199,13 @@ exports.arrayEqual = function(a, b){ * @param {Array} arr * @return {Array} */ -function cloneArray(arr){ +function cloneArray(arr) { if (!Array.isArray(arr)) throw new TypeError('arr must be an array!'); var len = arr.length; var result = new Array(len); - for (var i = 0; i < len; i++){ + for (var i = 0; i < len; i++) { result[i] = arr[i]; } @@ -223,14 +223,14 @@ exports.cloneArray = cloneArray; * @return {Boolean} * @static */ -exports.contains = function(arr, input){ +exports.contains = function(arr, input) { if (!Array.isArray(arr)) throw new TypeError('arr must be an array!'); var i = arr.length; if (!i) return false; - while (i--){ + while (i--) { if (arr[i] === input) return true; } @@ -245,7 +245,7 @@ exports.contains = function(arr, input){ * @return {Array} * @static */ -exports.reverse = function(arr){ +exports.reverse = function(arr) { if (!Array.isArray(arr)) throw new TypeError('arr must be an array!'); var len = arr.length; @@ -253,7 +253,7 @@ exports.reverse = function(arr){ if (!len) return arr; - for (var left = 0, right = len - 1; left < right; left++, right--){ + for (var left = 0, right = len - 1; left < right; left++, right--) { tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; @@ -270,7 +270,7 @@ exports.reverse = function(arr){ * @return {Array} * @static */ -exports.shuffle = function(arr){ +exports.shuffle = function(arr) { if (!Array.isArray(arr)) throw new TypeError('arr must be an array!'); var len = arr.length; @@ -278,7 +278,7 @@ exports.shuffle = function(arr){ if (!len) return arr; - while (len){ + while (len) { i = Math.random() * len | 0; tmp = arr[--len]; arr[len] = arr[i]; @@ -288,14 +288,14 @@ exports.shuffle = function(arr){ return arr; }; -function parseArgs(args){ +function parseArgs(args) { if (typeof args !== 'string') return args; var arr = args.split(' '); var result = {}; var key; - for (var i = 0, len = arr.length; i < len; i++){ + for (var i = 0, len = arr.length; i < len; i++) { key = arr[i]; switch (key[0]){ @@ -330,13 +330,13 @@ function parseArgs(args){ * @return {Object} * @static */ -exports.parseArgs = function(orderby, order){ +exports.parseArgs = function(orderby, order) { var result; - if (order){ + if (order) { result = {}; result[orderby] = order; - } else if (typeof orderby === 'string'){ + } else if (typeof orderby === 'string') { result = parseArgs(orderby); } else { result = orderby; @@ -353,19 +353,19 @@ exports.parseArgs = function(orderby, order){ * @param {Object} target * @return {Object} */ -exports.extend = function(target){ +exports.extend = function(target) { var length = arguments.length; var arg, key; - for (var i = 1; i < length; i++){ + for (var i = 1; i < length; i++) { arg = arguments[i]; - if (typeof arg === 'object'){ - for (key in arg){ + if (typeof arg === 'object') { + for (key in arg) { target[key] = arg[key]; } } } return target; -}; \ No newline at end of file +}; diff --git a/package.json b/package.json index df692fe1..1fbac420 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,10 @@ "lib": "./lib" }, "scripts": { - "test": "gulp test" + "eslint": "eslint .", + "jscs": "jscs .", + "test": "mocha test/index.js", + "test-cov": "istanbul cover --print both _mocha -- test/index.js" }, "repository": "tommy351/warehouse", "keywords": [ @@ -25,17 +28,11 @@ "lodash": "^3.0.0" }, "devDependencies": { - "benchmark": "^1.0.0", "chai": "^3.2.0", "colors": "^1.0.3", - "coveralls": "^2.11.2", - "del": "^1.2.1", - "gulp": "^3.8.9", - "gulp-istanbul": "^0.10.0", - "gulp-jshint": "^1.8.6", - "gulp-load-plugins": "^1.0.0-rc.1", - "gulp-mocha": "^2.0.0", - "jshint-stylish": "^2.0.1", + "eslint": "^1.9.0", + "istanbul": "^0.4.0", + "jscs": "^2.5.1", "mocha": "^2.0.1", "sinon": "^1.12.2" } diff --git a/test/.eslintrc b/test/.eslintrc new file mode 100644 index 00000000..7411927e --- /dev/null +++ b/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "extend": "../.eslintrc", + "rules": { + "no-unused-expressions": 0 + }, + "env": { + "mocha": true + } +} \ No newline at end of file diff --git a/test/fixtures/db.json b/test/fixtures/db.json index 8de61b22..8dacfb0f 100644 --- a/test/fixtures/db.json +++ b/test/fixtures/db.json @@ -1 +1 @@ -{"meta":{"version":1,"warehouse":"1.0.2"},"models":{"Test":[{"_id":"A"},{"_id":"B"},{"_id":"C"}]}} \ No newline at end of file +{"meta":{"version":1,"warehouse":"1.0.3"},"models":{"Test":[{"_id":"A"},{"_id":"B"},{"_id":"C"}]}} \ No newline at end of file diff --git a/test/index.js b/test/index.js index a5e99aed..dcf2303f 100644 --- a/test/index.js +++ b/test/index.js @@ -1,4 +1,6 @@ -describe('Warehouse', function(){ +'use strict'; + +describe('Warehouse', function() { require('./scripts/database'); require('./scripts/document'); require('./scripts/model'); @@ -17,4 +19,4 @@ describe('Warehouse', function(){ require('./scripts/types/string'); require('./scripts/types/virtual'); require('./scripts/util'); -}); \ No newline at end of file +}); diff --git a/test/mocha.opts b/test/mocha.opts new file mode 100644 index 00000000..fb5f8242 --- /dev/null +++ b/test/mocha.opts @@ -0,0 +1 @@ +--reporter spec \ No newline at end of file diff --git a/test/scripts/database.js b/test/scripts/database.js index 974e0952..384c3e7a 100644 --- a/test/scripts/database.js +++ b/test/scripts/database.js @@ -1,4 +1,6 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var path = require('path'); var Promise = require('bluebird'); var sinon = require('sinon'); @@ -7,7 +9,7 @@ var fs = Promise.promisifyAll(require('fs')); var DB_PATH = path.join(path.dirname(__dirname), 'fixtures', 'db.json'); var DB_VERSION = 1; -describe('Database', function(){ +describe('Database', function() { var Database = require('../..'); var Model = require('../../lib/model'); var Schema = Database.Schema; @@ -17,7 +19,7 @@ describe('Database', function(){ _id: {type: String, required: true} })); - before(function(){ + before(function() { return TestModel.insert([ {_id: 'A'}, {_id: 'B'}, @@ -25,22 +27,22 @@ describe('Database', function(){ ]); }); - it('model() - get', function(){ + it('model() - get', function() { var Test = db.model('Test'); Test.data.should.eql(TestModel.data); }); - it('model() - create', function(){ + it('model() - create', function() { var Post = db.model('Post'); Post.should.be.an.instanceOf(Model); db._models.Post.should.exist; Post.destroy(); }); - it('load()', function(){ + it('load()', function() { var db = new Database({path: DB_PATH}); - return db.load().then(function(){ + return db.load().then(function() { var Test = db.model('Test'); Test.toArray().should.eql([ @@ -51,8 +53,8 @@ describe('Database', function(){ }); }); - it('load() - upgrade', function(){ - var onUpgrade = sinon.spy(function(oldVersion, newVersion){ + it('load() - upgrade', function() { + var onUpgrade = sinon.spy(function(oldVersion, newVersion) { oldVersion.should.eql(DB_VERSION); newVersion.should.eql(2); }); @@ -63,13 +65,13 @@ describe('Database', function(){ onUpgrade: onUpgrade }); - return db.load().then(function(){ + return db.load().then(function() { onUpgrade.calledOnce.should.be.true; }); }); - it('load() - downgrade', function(){ - var onDowngrade = sinon.spy(function(oldVersion, newVersion){ + it('load() - downgrade', function() { + var onDowngrade = sinon.spy(function(oldVersion, newVersion) { oldVersion.should.eql(DB_VERSION); newVersion.should.eql(0); }); @@ -80,15 +82,15 @@ describe('Database', function(){ onDowngrade: onDowngrade }); - return db.load().then(function(){ + return db.load().then(function() { onDowngrade.calledOnce.should.be.true; }); }); - it('save()', function(){ - return db.save().then(function(){ + it('save()', function() { + return db.save().then(function() { return fs.readFileAsync(DB_PATH, 'utf8'); - }).then(function(data){ + }).then(function(data) { var json = JSON.parse(data); json.meta.should.eql({ @@ -105,4 +107,4 @@ describe('Database', function(){ }); }); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/document.js b/test/scripts/document.js index 1001e6b9..a50e749f 100644 --- a/test/scripts/document.js +++ b/test/scripts/document.js @@ -1,8 +1,9 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var _ = require('lodash'); -var Promise = require('bluebird'); -describe('Document', function(){ +describe('Document', function() { var Database = require('../..'); var Document = require('../../lib/document'); var db = new Database(); @@ -19,7 +20,7 @@ describe('Document', function(){ author: {type: Schema.Types.CUID, ref: 'User'} }); - it('constructor', function(){ + it('constructor', function() { var doc = User.new({ name: 'John', age: 20 @@ -30,116 +31,117 @@ describe('Document', function(){ doc.age.should.eql(20); }); - it('constructor - no arguments', function(){ + it('constructor - no arguments', function() { var doc = User.new(); doc.should.be.an.instanceOf(Document); }); - it('save() - insert', function(){ + it('save() - insert', function() { var doc = User.new({}); - return doc.save().then(function(item){ + return doc.save().then(function(item) { User.findById(doc._id).should.exist; return User.removeById(item._id); }); }); - it('save() - replace', function(){ - return User.insert({}).then(function(doc){ + it('save() - replace', function() { + return User.insert({}).then(function(doc) { doc.name = 'A'; return doc.save(); - }).then(function(doc){ + }).then(function(doc) { doc.name.should.eql('A'); return User.removeById(doc._id); }); }); - it('update()', function(){ - return User.insert({}).then(function(doc){ + it('update()', function() { + return User.insert({}).then(function(doc) { return doc.update({name: 'A'}); - }).then(function(doc){ + }).then(function(doc) { doc.name.should.eql('A'); return User.removeById(doc._id); }); }); - it('replace()', function(){ - return User.insert({}).then(function(doc){ + it('replace()', function() { + return User.insert({}).then(function(doc) { return doc.replace({name: 'A'}); - }).then(function(doc){ + }).then(function(doc) { doc.name.should.eql('A'); return User.removeById(doc._id); }); }); - it('remove()', function(){ - return User.insert({}).then(function(doc){ + it('remove()', function() { + return User.insert({}).then(function(doc) { return doc.remove(); - }).then(function(doc){ + }).then(function(doc) { should.not.exist(User.findById(doc._id)); }); }); - it('toObject()', function(){ + it('toObject()', function() { var doc = User.new({}); doc.toObject().should.not.be.instanceOf(User.Document); }); - it('toObject() - don\'t deep clone getters', function(){ + it('toObject() - don\'t deep clone getters', function() { var db = new Database(); + var User; var userSchema = new Schema({ name: String, age: Number }); - userSchema.virtual('users').get(function(){ + userSchema.virtual('users').get(function() { return User.find({}); }); - var User = db.model('User', userSchema); + User = db.model('User', userSchema); - return User.insert({}).then(function(data){ + return User.insert({}).then(function(data) { return User.findById(data._id); - }).then(function(data){ + }).then(function(data) { data.toObject().should.be.ok; }); }); - it('toString()', function(){ + it('toString()', function() { var doc = User.new({}); doc.toString().should.eql(JSON.stringify(doc)); }); - it('populate() - object', function(){ - return User.insert({}).then(function(user){ + it('populate() - object', function() { + return User.insert({}).then(function(user) { var comment = Comment.new({ author: user._id }); comment.populate('author').author.should.eql(user); return user; - }).then(function(user){ + }).then(function(user) { return User.removeById(user._id); }); }); - it('populate() - array', function(){ + it('populate() - array', function() { return Comment.insert([ {content: 'foo'}, {content: 'bar'}, {content: 'baz'}, {content: 'ha'} - ]).then(function(comments){ + ]).then(function(comments) { var user = User.new({ comments: _.map(comments, '_id') }); user.populate('comments').comments.toArray().should.eql(comments); return comments; - }).map(function(comment){ + }).map(function(comment) { return Comment.removeById(comment._id); }); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/model.js b/test/scripts/model.js index b9cd61da..020dbc1d 100644 --- a/test/scripts/model.js +++ b/test/scripts/model.js @@ -1,11 +1,13 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var _ = require('lodash'); var Promise = require('bluebird'); var sinon = require('sinon'); var WarehouseError = require('../../lib/error'); var util = require('util'); -describe('Model', function(){ +describe('Model', function() { var Database = require('../..'); var Schema = Database.Schema; var SchemaType = Database.SchemaType; @@ -22,7 +24,7 @@ describe('Model', function(){ posts: [{type: Schema.Types.CUID, ref: 'Post'}] }); - userSchema.virtual('name.full').get(function(){ + userSchema.virtual('name.full').get(function() { return this.name.first + ' ' + this.name.last; }); @@ -36,7 +38,7 @@ describe('Model', function(){ var User = db.model('User', userSchema); var Post = db.model('Post', postSchema); - it('new()', function(){ + it('new()', function() { var user = User.new({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', @@ -52,34 +54,34 @@ describe('Model', function(){ user.posts.should.eql([]); }); - it('findById()', function(){ + it('findById()', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { User.findById(data._id).should.eql(data); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('findById() - lean', function(){ + it('findById() - lean', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { User.findById(data._id, {lean: true}).name.should.not.ownProperty('full'); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('insert()', function(){ - var listener = sinon.spy(function(data){ + it('insert()', function() { + var listener = sinon.spy(function(data) { User.findById(data._id).should.exist; }); @@ -89,52 +91,53 @@ describe('Model', function(){ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { User.findById(data._id).should.exist; User.length.should.eql(1); listener.calledOnce.should.be.true; return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('insert() - no id', function(){ + it('insert() - no id', function() { var doc = User.new(); delete doc._id; - return User.insert(doc).catch(function(err){ + return User.insert(doc).catch(function(err) { err.should.be .instanceOf(WarehouseError) .property('message', 'ID is not defined'); }); }); - it('insert() - already existed', function(){ + it('insert() - already existed', function() { var user; - return User.insert({}).then(function(data){ + return User.insert({}).then(function(data) { user = data; return User.insert(data); - }).finally(function(){ + }).finally(function() { return User.removeById(user._id); - }).catch(function(err){ + }).catch(function(err) { err.should.be .instanceOf(WarehouseError) .property('message', 'ID `' + user._id + '` has been used'); }); }); - it('insert() - hook', function(){ + it('insert() - hook', function() { var db = new Database(); var testSchema = new Schema(); + var Test; - var preHook = sinon.spy(function(data){ + var preHook = sinon.spy(function(data) { should.not.exist(Test.findById(data._id)); data.foo.should.eql('bar'); }); - var postHook = sinon.spy(function(data){ + var postHook = sinon.spy(function(data) { Test.findById(data._id).should.exist; data.foo.should.eql('bar'); }); @@ -142,15 +145,15 @@ describe('Model', function(){ testSchema.pre('save', preHook); testSchema.post('save', postHook); - var Test = db.model('Test', testSchema); + Test = db.model('Test', testSchema); - return Test.insert({foo: 'bar'}).then(function(){ + return Test.insert({foo: 'bar'}).then(function() { preHook.calledOnce.should.be.true; postHook.calledOnce.should.be.true; }); }); - it('insert() - array', function(){ + it('insert() - array', function() { return User.insert([ { name: {first: 'John', last: 'Doe'}, @@ -162,65 +165,66 @@ describe('Model', function(){ email: 'andy@example.com', age: 30 } - ]).then(function(data){ + ]).then(function(data) { data.length = 2; return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('insert() - sync problem', function(callback){ + it('insert() - sync problem', function(callback) { var db = new Database(); var testSchema = new Schema(); + var Test; - testSchema.pre('save', function(data){ + testSchema.pre('save', function(data) { var item = Test.findOne({id: data.id}); if (item) throw new Error('ID "' + data.id + '" has been used.'); }); - var Test = db.model('Test', testSchema); + Test = db.model('Test', testSchema); Test.insert([ {id: 1}, {id: 1} - ]).catch(function(err){ + ]).catch(function(err) { err.should.have.property('message', 'ID "1" has been used.'); callback(); }); }); - it('save() - insert', function(){ + it('save() - insert', function() { return User.save({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { User.findById(data._id).should.exist; return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('save() - replace', function(){ + it('save() - replace', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { data.age = 30; return User.save(data); - }).then(function(data){ + }).then(function(data) { data.age.should.eql(30); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById()', function(){ - var listener = sinon.spy(function(data){ + it('updateById()', function() { + var listener = sinon.spy(function(data) { User.findById(data._id).age.should.eql(30); }); @@ -230,175 +234,175 @@ describe('Model', function(){ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {age: 30}); - }).then(function(data){ + }).then(function(data) { data.age.should.eql(30); listener.calledOnce.should.be.true; return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - object', function(){ + it('updateById() - object', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {name: {first: 'Jerry'}}); - }).then(function(data){ + }).then(function(data) { data.name.first.should.eql('Jerry'); data.name.last.should.eql('Doe'); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - dot notation', function(){ + it('updateById() - dot notation', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {'name.last': 'Smith'}); - }).then(function(data){ + }).then(function(data) { data.name.first.should.eql('John'); data.name.last.should.eql('Smith'); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - operator', function(){ + it('updateById() - operator', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {age: {$inc: 5}}); - }).then(function(data){ + }).then(function(data) { data.age.should.eql(25); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - operator in first class', function(){ + it('updateById() - operator in first class', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {$inc: {age: 5}}); - }).then(function(data){ + }).then(function(data) { data.age.should.eql(25); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - $set', function(){ + it('updateById() - $set', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {$set: {age: 25}}); - }).then(function(data){ + }).then(function(data) { data.age.should.eql(25); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - $unset', function(){ + it('updateById() - $unset', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {$unset: {email: true}}); - }).then(function(data){ + }).then(function(data) { should.not.exist(data.email); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - $unset false', function(){ + it('updateById() - $unset false', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {$unset: {email: false}}); - }).then(function(data){ + }).then(function(data) { data.email.should.eql('abc@example.com'); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - $rename', function(){ + it('updateById() - $rename', function() { return User.insert({ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.updateById(data._id, {$rename: {email: 'address'}}); - }).then(function(data){ + }).then(function(data) { data.address.should.eql('abc@example.com'); should.not.exist(data.email); return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('updateById() - id not exist', function(){ - return User.updateById('foo', {}).catch(function(err){ + it('updateById() - id not exist', function() { + return User.updateById('foo', {}).catch(function(err) { err.should.be .instanceOf(WarehouseError) .property('message', 'ID `foo` does not exist'); }); }); - it('updateById() - hook', function(){ + it('updateById() - hook', function() { var db = new Database(); var testSchema = new Schema(); var Test = db.model('Test', testSchema); - var preHook = sinon.spy(function(data){ + var preHook = sinon.spy(function(data) { should.not.exist(Test.findById(data._id).baz); }); - var postHook = sinon.spy(function(data){ + var postHook = sinon.spy(function(data) { Test.findById(data._id).baz.should.eql(1); }); return Test.insert({ foo: 'bar' - }).then(function(data){ + }).then(function(data) { testSchema.pre('save', preHook); testSchema.post('save', postHook); return Test.updateById(data._id, {baz: 1}); - }).then(function(){ + }).then(function() { preHook.calledOnce.should.be.true; postHook.calledOnce.should.be.true; }); }); - it('update()', function(){ + it('update()', function() { return User.insert([ {age: 10}, {age: 20}, @@ -406,27 +410,27 @@ describe('Model', function(){ {age: 20}, {age: 40} ]).then(function(data) { - return User.update({age: 20}, {email: 'A'}).then(function(updated){ + return User.update({age: 20}, {email: 'A'}).then(function(updated) { updated[0]._id.should.eql(data[1]._id); updated[1]._id.should.eql(data[3]._id); updated[0].email.should.eql('A'); updated[1].email.should.eql('A'); return data; }); - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('replaceById()', function(){ - function validate(data){ + it('replaceById()', function() { + function validate(data) { data.name.first.should.eql('Mary'); data.name.last.should.eql('White'); data.age.should.eql(40); data.should.not.ownProperty('email'); } - var listener = sinon.spy(function(data){ + var listener = sinon.spy(function(data) { validate(User.findById(data._id)); }); @@ -441,50 +445,50 @@ describe('Model', function(){ name: {first: 'Mary', last: 'White'}, age: 40 }); - }).then(function(data){ + }).then(function(data) { validate(data); listener.calledOnce.should.be.true; return data; - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); }); }); - it('replaceById() - id not exist', function(){ - return User.replaceById('foo', {}).catch(function(err){ + it('replaceById() - id not exist', function() { + return User.replaceById('foo', {}).catch(function(err) { err.should.be .instanceOf(WarehouseError) .property('message', 'ID `foo` does not exist'); }); }); - it('replaceById() - pre-hook', function(){ + it('replaceById() - pre-hook', function() { var db = new Database(); var testSchema = new Schema(); var Test = db.model('Test', testSchema); - var preHook = sinon.spy(function(data){ + var preHook = sinon.spy(function(data) { Test.findById(data._id).foo.should.eql('bar'); }); - var postHook = sinon.spy(function(data){ + var postHook = sinon.spy(function(data) { Test.findById(data._id).foo.should.eql('baz'); }); return Test.insert({ foo: 'bar' - }).then(function(data){ + }).then(function(data) { testSchema.pre('save', preHook); testSchema.post('save', postHook); return Test.replaceById(data._id, {foo: 'baz'}); - }).then(function(){ + }).then(function() { preHook.calledOnce.should.be.true; postHook.calledOnce.should.be.true; }); }); - it('replace()', function(){ + it('replace()', function() { return User.insert([ {age: 10}, {age: 20}, @@ -492,20 +496,20 @@ describe('Model', function(){ {age: 20}, {age: 40} ]).then(function(data) { - return User.replace({age: 20}, {email: 'A'}).then(function(updated){ + return User.replace({age: 20}, {email: 'A'}).then(function(updated) { updated[0]._id.should.eql(data[1]._id); updated[1]._id.should.eql(data[3]._id); updated[0].email.should.eql('A'); updated[1].email.should.eql('A'); return data; }); - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('removeById()', function(){ - var listener = sinon.spy(function(data){ + it('removeById()', function() { + var listener = sinon.spy(function(data) { should.not.exist(User.findById(data._id)); }); @@ -515,32 +519,32 @@ describe('Model', function(){ name: {first: 'John', last: 'Doe'}, email: 'abc@example.com', age: 20 - }).then(function(data){ + }).then(function(data) { return User.removeById(data._id); - }).then(function(data){ + }).then(function(data) { listener.calledOnce.should.be.true; should.not.exist(User.findById(data._id)); - }) + }); }); - it('removeById() - id not exist', function(){ - return User.removeById('foo', {}).catch(function(err){ + it('removeById() - id not exist', function() { + return User.removeById('foo', {}).catch(function(err) { err.should.be .instanceOf(WarehouseError) .property('message', 'ID `foo` does not exist'); }); }); - it('removeById() - hook', function(){ + it('removeById() - hook', function() { var db = new Database(); var testSchema = new Schema(); var Test = db.model('Test', testSchema); - var preHook = sinon.spy(function(data){ + var preHook = sinon.spy(function(data) { Test.findById(data._id).should.exist; }); - var postHook = sinon.spy(function(data){ + var postHook = sinon.spy(function(data) { should.not.exist(Test.findById(data._id)); }); @@ -549,140 +553,136 @@ describe('Model', function(){ return Test.insert({ foo: 'bar' - }).then(function(data){ + }).then(function(data) { return Test.removeById(data._id); - }).then(function(){ + }).then(function() { preHook.calledOnce.should.be.true; postHook.calledOnce.should.be.true; }); }); - it('remove()', function(){ + it('remove()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 20}, {age: 40} - ]).then(function(data){ - return User.remove({age: 20}).then(function(removed){ + ]).then(function(data) { + return User.remove({age: 20}).then(function(removed) { should.not.exist(User.findById(data[1]._id)); should.not.exist(User.findById(data[3]._id)); return [data[0], data[2], data[4]]; }); - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('destroy()', function(){ + it('destroy()', function() { var Test = db.model('Test'); Test.destroy(); should.not.exist(db._models.Test); }); - it('count()', function(){ + it('count()', function() { Post.length.should.eql(Post.count()); }); - it('forEach()', function(){ + it('forEach()', function() { var count = 0; - return Post.insert([ - {}, {}, {}, {}, {}, {}, {}, {}, {}, {} - ]).then(function(data){ - Post.forEach(function(item, i){ + return Post.insert(_.fill(Array(10), {})).then(function(data) { + Post.forEach(function(item, i) { item.should.eql(data[i]); i.should.eql(count++); }); count.should.eql(data.length); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('toArray()', function(){ - return Post.insert([ - {}, {}, {}, {}, {}, {}, {}, {}, {}, {} - ]).then(function(data){ + it('toArray()', function() { + return Post.insert(_.fill(Array(10), {})).then(function(data) { Post.toArray().should.eql(data); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('find()', function(){ + it('find()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({age: 20}); query.data.should.eql(data.slice(1, 3)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - blank', function(){ + it('find() - blank', function() { return User.insert([ {age: 10}, {age: 20}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}); query.data.should.eql(data); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - operator', function(){ + it('find() - operator', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({age: {$gt: 20}}); query.data.should.eql(data.slice(2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - limit', function(){ + it('find() - limit', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({age: {$gte: 20}}, {limit: 2}); query.data.should.eql(data.slice(1, 3)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - skip', function(){ + it('find() - skip', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({age: {$gte: 20}}, {skip: 1}); query.data.should.eql(data.slice(2)); @@ -691,32 +691,32 @@ describe('Model', function(){ query.data.should.eql(data.slice(2, 3)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - lean', function(){ + it('find() - lean', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({age: {$gt: 20}}, {lean: true}); query.should.be.a('array'); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $and', function(){ + it('find() - $and', function() { return User.insert([ {name: {first: 'John', last: 'Doe'}, age: 20}, {name: {first: 'Jane', last: 'Doe'}, age: 25}, {name: {first: 'Jack', last: 'White'}, age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({ $and: [ {'name.last': 'Doe'}, @@ -727,17 +727,17 @@ describe('Model', function(){ query.toArray().should.eql([data[1]]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $or', function(){ + it('find() - $or', function() { return User.insert([ {name: {first: 'John', last: 'Doe'}, age: 20}, {name: {first: 'Jane', last: 'Doe'}, age: 25}, {name: {first: 'Jack', last: 'White'}, age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({ $or: [ {'name.last': 'White'}, @@ -748,17 +748,17 @@ describe('Model', function(){ query.toArray().should.eql(data.slice(1)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $nor', function(){ + it('find() - $nor', function() { return User.insert([ {name: {first: 'John', last: 'Doe'}, age: 20}, {name: {first: 'Jane', last: 'Doe'}, age: 25}, {name: {first: 'Jack', last: 'White'}, age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({ $nor: [ {'name.last': 'White'}, @@ -769,17 +769,17 @@ describe('Model', function(){ query.toArray().should.eql([data[0]]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $not', function(){ + it('find() - $not', function() { return User.insert([ {name: {first: 'John', last: 'Doe'}, age: 20}, {name: {first: 'Jane', last: 'Doe'}, age: 25}, {name: {first: 'Jack', last: 'White'}, age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({ $not: {'name.last': 'Doe'} }); @@ -787,19 +787,19 @@ describe('Model', function(){ query.toArray().should.eql(data.slice(2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $where', function(){ + it('find() - $where', function() { return User.insert([ {name: {first: 'John', last: 'Doe'}, age: 20}, {name: {first: 'Jane', last: 'Doe'}, age: 25}, {name: {first: 'Jack', last: 'White'}, age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({ - $where: function(){ + $where: function() { return this.name.last === 'Doe'; } }); @@ -807,322 +807,286 @@ describe('Model', function(){ query.toArray().should.eql(data.slice(0, 2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('findOne()', function(){ + it('findOne()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { User.findOne({age: {$gt: 20}}).should.eql(data[2]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('findOne() - lean', function(){ + it('findOne() - lean', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { User.findOne({age: {$gt: 20}}, {lean: true})._id.should.eql(data[2]._id); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('sort()', function(){ + it('sort()', function() { return User.insert([ {age: 15}, {age: 35}, {age: 10} - ]).then(function(data){ + ]).then(function(data) { var query = User.sort('age'); query.data[0].should.eql(data[2]); query.data[1].should.eql(data[0]); query.data[2].should.eql(data[1]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('sort() - descending', function(){ + it('sort() - descending', function() { return User.insert([ {age: 15}, {age: 35}, {age: 10} - ]).then(function(data){ + ]).then(function(data) { var query = User.sort('age', -1); query.data[0].should.eql(data[1]); query.data[1].should.eql(data[0]); query.data[2].should.eql(data[2]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('sort() - multi', function(){ + it('sort() - multi', function() { return User.insert([ {age: 15, email: 'A'}, {age: 30, email: 'B'}, {age: 20, email: 'C'}, {age: 20, email: 'D'} - ]).then(function(data){ + ]).then(function(data) { var query = User.sort('age email'); query.data[0].should.eql(data[0]); query.data[1].should.eql(data[2]); query.data[2].should.eql(data[3]); query.data[3].should.eql(data[1]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('eq()', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ - for (var i = 0, len = data.length; i < len; i++){ + it('eq()', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { + for (var i = 0, len = data.length; i < len; i++) { Post.eq(i).should.eql(data[i]); } return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('eq() - negative index', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ - for (var i = 1, len = data.length; i <= len; i++){ + it('eq() - negative index', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { + for (var i = 1, len = data.length; i <= len; i++) { Post.eq(-i).should.eql(data[len - i]); } return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('first()', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('first()', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.first().should.eql(data[0]); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('last()', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('last()', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.last().should.eql(data[data.length - 1]); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - no arguments', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - no arguments', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice().data.should.eql(data); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - one argument', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - one argument', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice(2).data.should.eql(data.slice(2)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - one negative argument', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - one negative argument', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice(-2).data.should.eql(data.slice(-2)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - two arguments', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - two arguments', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice(2, 4).data.should.eql(data.slice(2, 4)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - start + negative end index', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - start + negative end index', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice(1, -1).data.should.eql(data.slice(1, -1)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - two negative arguments', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - two negative arguments', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice(-3, -1).data.should.eql(data.slice(-3, -1)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - start > end', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - start > end', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice(-1, -3).data.should.eql(data.slice(-1, -3)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - index overflow', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - index overflow', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice(1, 100).data.should.eql(data.slice(1, 100)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('slice() - index overflow 2', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice() - index overflow 2', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.slice(100, 200).data.should.eql(data.slice(100, 200)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('limit()', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('limit()', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.limit(2).data.should.eql(data.slice(0, 2)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('skip()', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('skip()', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { Post.skip(2).data.should.eql(data.slice(2)); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('reverse()', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('reverse()', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { var query = Post.reverse(); - for (var i = 0, len = data.length; i < len; i++){ + for (var i = 0, len = data.length; i < len; i++) { query.data[i].should.eql(data[len - i - 1]); } return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('shuffle()', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('shuffle()', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { var query = Post.shuffle(); _.sortBy(query.data, '_id').should.eql(_.sortBy(data, '_id')); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('map()', function(){ - return Post.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('map()', function() { + return Post.insert(_.fill(Array(5), {})).then(function(data) { var num = 0; - var d1 = Post.map(function(item, i){ + var d1 = Post.map(function(item, i) { i.should.eql(num++); return item._id; }); - var d2 = data.map(function(item){ + var d2 = data.map(function(item) { return item._id; }); d1.should.eql(d2); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('reduce()', function(){ + it('reduce()', function() { return Post.insert([ {email: 'A'}, {email: 'B'}, {email: 'C'} - ]).then(function(data){ + ]).then(function(data) { var num = 1; - var sum = Post.reduce(function(sum, item, i){ + var sum = Post.reduce(function(sum, item, i) { i.should.eql(num++); return {email: sum.email + item.email}; }); @@ -1130,20 +1094,20 @@ describe('Model', function(){ sum.email.should.eql('ABC'); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('reduce() - with initial', function(){ + it('reduce() - with initial', function() { return Post.insert([ {email: 'A'}, {email: 'B'}, {email: 'C'} - ]).then(function(data){ + ]).then(function(data) { var num = 0; - var sum = Post.reduce(function(sum, item, i){ + var sum = Post.reduce(function(sum, item, i) { i.should.eql(num++); return sum + item.email; }, '_'); @@ -1151,20 +1115,20 @@ describe('Model', function(){ sum.should.eql('_ABC'); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('reduceRight()', function(){ + it('reduceRight()', function() { return Post.insert([ {email: 'A'}, {email: 'B'}, {email: 'C'} - ]).then(function(data){ + ]).then(function(data) { var num = 1; - var sum = Post.reduceRight(function(sum, item, i){ + var sum = Post.reduceRight(function(sum, item, i) { i.should.eql(num--); return {email: sum.email + item.email}; }); @@ -1172,20 +1136,20 @@ describe('Model', function(){ sum.email.should.eql('CBA'); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('reduceRight() - with initial', function(){ + it('reduceRight() - with initial', function() { return Post.insert([ {email: 'A'}, {email: 'B'}, {email: 'C'} - ]).then(function(data){ + ]).then(function(data) { var num = 2; - var sum = Post.reduceRight(function(sum, item, i){ + var sum = Post.reduceRight(function(sum, item, i) { i.should.eql(num--); return sum + item.email; }, '_'); @@ -1193,21 +1157,21 @@ describe('Model', function(){ sum.should.eql('_CBA'); return data; - }).map(function(item){ + }).map(function(item) { return Post.removeById(item._id); }); }); - it('filter()', function(){ + it('filter()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var num = 0; - var query = User.filter(function(data, i){ + var query = User.filter(function(data, i) { i.should.eql(num++); return data.age > 20; }); @@ -1215,72 +1179,72 @@ describe('Model', function(){ query.data.should.eql(data.slice(2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('every()', function(){ + it('every()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var num = 0; - User.every(function(data, i){ + User.every(function(data, i) { i.should.eql(num++); return data.age; }).should.be.true; - User.every(function(data, i){ + User.every(function(data, i) { return data.age > 10; }).should.be.false; return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('some()', function(){ + it('some()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var num = 0; - User.some(function(data, i){ + User.some(function(data, i) { return data.age > 10; }).should.be.true; - User.some(function(data, i){ + User.some(function(data, i) { i.should.eql(num++); return data.age < 0; }).should.be.false; return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('populate() - object', function(){ + it('populate() - object', function() { var user, post; - return User.insert({}).then(function(user_){ + return User.insert({}).then(function(user_) { user = user_; return Post.insert({ user_id: user_._id }); - }).then(function(post_){ + }).then(function(post_) { post = post_; return Post.populate('user_id'); - }).then(function(result){ + }).then(function(result) { result.first().user_id.should.eql(user); return Promise.all([ @@ -1290,7 +1254,7 @@ describe('Model', function(){ }); }); - it('populate() - array', function(){ + it('populate() - array', function() { var posts, user; return Post.insert([ @@ -1298,16 +1262,16 @@ describe('Model', function(){ {title: 'ACD'}, {title: 'CDE'}, {title: 'XYZ'} - ]).then(function(posts_){ + ]).then(function(posts_) { posts = posts_; return User.insert({ posts: _.map(posts, '_id') }); - }).then(function(user_){ + }).then(function(user_) { user = user_; return User.populate('posts'); - }).then(function(result){ + }).then(function(result) { var query = result.first().posts; query.should.be.an.instanceOf(Post.Query); @@ -1323,7 +1287,7 @@ describe('Model', function(){ }); }); - it('populate() - match', function(){ + it('populate() - match', function() { var posts, user; return Post.insert([ @@ -1331,19 +1295,19 @@ describe('Model', function(){ {title: 'ACD'}, {title: 'CDE'}, {title: 'XYZ'} - ]).then(function(posts_){ + ]).then(function(posts_) { posts = posts_; return User.insert({ posts: _.map(posts, '_id') }); - }).then(function(user_){ + }).then(function(user_) { user = user_; return User.populate({ path: 'posts', match: {title: /^A/} }); - }).then(function(result){ + }).then(function(result) { result.first().posts.toArray().should.eql(posts.slice(0, 2)); return Promise.all([ @@ -1356,7 +1320,7 @@ describe('Model', function(){ }); }); - it('populate() - sort', function(){ + it('populate() - sort', function() { var posts, user; return Post.insert([ @@ -1364,22 +1328,25 @@ describe('Model', function(){ {title: 'ABCD'}, {title: 'CDE'}, {title: 'ACD'} - ]).then(function(posts_){ + ]).then(function(posts_) { posts = posts_; return User.insert({ posts: _.map(posts, '_id') }); - }).then(function(user_){ + }).then(function(user_) { user = user_; return User.populate({ path: 'posts', sort: 'title' }); - }).then(function(result){ + }).then(function(result) { result.first().posts.toArray().should.eql([ - posts[1], posts[3], posts[2], posts[0] + posts[1], + posts[3], + posts[2], + posts[0] ]); return Promise.all([ @@ -1392,7 +1359,7 @@ describe('Model', function(){ }); }); - it('populate() - limit', function(){ + it('populate() - limit', function() { var posts, user; return Post.insert([ @@ -1400,20 +1367,20 @@ describe('Model', function(){ {title: 'ABCD'}, {title: 'CDE'}, {title: 'ACD'} - ]).then(function(posts_){ + ]).then(function(posts_) { posts = posts_; return User.insert({ posts: _.map(posts, '_id') }); - }).then(function(user_){ + }).then(function(user_) { user = user_; return User.populate({ path: 'posts', limit: 2 }); - }).then(function(result){ + }).then(function(result) { result.first().posts.toArray().should.eql(posts.slice(0, 2)); // with match @@ -1422,7 +1389,7 @@ describe('Model', function(){ match: {title: /D/}, limit: 2 }); - }).then(function(result){ + }).then(function(result) { result.first().posts.toArray().should.eql(posts.slice(1, 3)); return Promise.all([ @@ -1435,7 +1402,7 @@ describe('Model', function(){ }); }); - it('populate() - skip', function(){ + it('populate() - skip', function() { var posts, user; return Post.insert([ @@ -1443,20 +1410,20 @@ describe('Model', function(){ {title: 'ABCD'}, {title: 'CDE'}, {title: 'ACD'} - ]).then(function(posts_){ + ]).then(function(posts_) { posts = posts_; return User.insert({ posts: _.map(posts, '_id') }); - }).then(function(user_){ + }).then(function(user_) { user = user_; return User.populate({ path: 'posts', skip: 2 }); - }).then(function(result){ + }).then(function(result) { result.first().posts.toArray().should.eql(posts.slice(2)); // with match @@ -1465,7 +1432,7 @@ describe('Model', function(){ match: {title: /D/}, skip: 2 }); - }).then(function(result){ + }).then(function(result) { result.first().posts.toArray().should.eql(posts.slice(3)); // with limit @@ -1474,7 +1441,7 @@ describe('Model', function(){ limit: 2, skip: 1 }); - }).then(function(result){ + }).then(function(result) { result.first().posts.toArray().should.eql(posts.slice(1, 3)); // with match & limit @@ -1484,7 +1451,7 @@ describe('Model', function(){ limit: 2, skip: 1 }); - }).then(function(result){ + }).then(function(result) { result.first().posts.toArray().should.eql(posts.slice(2)); return Promise.all([ @@ -1497,39 +1464,39 @@ describe('Model', function(){ }); }); - it('static method', function(){ + it('static method', function() { var schema = new Schema(); - schema.static('add', function(value){ + schema.static('add', function(value) { return this.insert(value); }); var Test = db.model('Test', schema); - Test.add({name: 'foo'}).then(function(data){ + Test.add({name: 'foo'}).then(function(data) { data.name.should.eql('foo'); }); Test.destroy(); }); - it('instance method', function(){ + it('instance method', function() { var schema = new Schema(); - schema.method('getName', function(){ + schema.method('getName', function() { return this.name; }); var Test = db.model('Test', schema); - Test.insert({name: 'foo'}).then(function(data){ + Test.insert({name: 'foo'}).then(function(data) { data.getName().should.eql('foo'); }); Test.destroy(); }); - it('_import()', function(){ + it('_import()', function() { var schema = new Schema({ _id: {type: String, required: true}, bool: Boolean @@ -1552,7 +1519,7 @@ describe('Model', function(){ Test.destroy(); }); - it('_export()', function(){ + it('_export()', function() { var schema = new Schema({ _id: {type: String, required: true}, bool: Boolean @@ -1563,7 +1530,7 @@ describe('Model', function(){ return Test.insert([ {_id: 'A', bool: true}, {_id: 'B', bool: false} - ]).then(function(data){ + ]).then(function(data) { Test._export().should.eql(JSON.stringify([ {_id: 'A', bool: 1}, {_id: 'B', bool: 0} @@ -1573,14 +1540,14 @@ describe('Model', function(){ }); }); - it('_export() - should not save undefined value', function(){ - var CacheType = function(){ + it('_export() - should not save undefined value', function() { + var CacheType = function() { SchemaType.apply(this, arguments); }; util.inherits(CacheType, SchemaType); - CacheType.prototype.value = function(){ + CacheType.prototype.value = function() { return; }; @@ -1592,11 +1559,11 @@ describe('Model', function(){ return Test.insert({ cache: 'test' - }).then(function(data){ + }).then(function(data) { data.cache.should.exist; should.not.exist(JSON.parse(Test._export())[0].cache); return Test.destroy(); }); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/query.js b/test/scripts/query.js index f4993172..d5d25590 100644 --- a/test/scripts/query.js +++ b/test/scripts/query.js @@ -1,8 +1,10 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var _ = require('lodash'); var Promise = require('bluebird'); -describe('Query', function(){ +describe('Query', function() { var Database = require('../..'); var db = new Database(); var Schema = Database.Schema; @@ -18,223 +20,199 @@ describe('Query', function(){ author: {type: Schema.Types.CUID, ref: 'User'} }); - it('count()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('count()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { User.find({}).count().should.eql(data.length); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('forEach()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('forEach()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { var count = 0; - User.find({}).forEach(function(item, i){ + User.find({}).forEach(function(item, i) { item.should.eql(data[i]); i.should.eql(count++); }); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('toArray()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('toArray()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { User.find({}).toArray().should.eql(data); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('eq()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('eq()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { var query = User.find({}); - for (var i = 0, len = data.length; i < len; i++){ + for (var i = 0, len = data.length; i < len; i++) { query.eq(i).should.eql(data[i]); } return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('eq() - negative index', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('eq() - negative index', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { var query = User.find({}); - for (var i = 1, len = data.length; i <= len; i++){ + for (var i = 1, len = data.length; i <= len; i++) { query.eq(-i).should.eql(data[len - i]); } return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('first()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('first()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { User.find({}).first().should.eql(data[0]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('last()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('last()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { User.find({}).last().should.eql(data[data.length - 1]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('slice()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('slice()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { User.find({}).slice(2, 4).data.should.eql(data.slice(2, 4)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('limit()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('limit()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { User.find({}).limit(2).data.should.eql(data.slice(0, 2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('skip()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('skip()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { User.find({}).skip(2).data.should.eql(data.slice(2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('reverse()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('reverse()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { User.find({}).reverse().data.should.eql(data.reverse()); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('shuffle()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('shuffle()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { _.sortBy(User.find({}).shuffle().data, '_id').should.eql(_.sortBy(data, '_id')); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find()', function(){ + it('find()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({age: 20}); query.data.should.eql(data.slice(1, 3)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - blank', function(){ + it('find() - blank', function() { return User.insert([ {age: 10}, {age: 20}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({}); query.data.should.eql(data); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - operator', function(){ + it('find() - operator', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({age: {$gt: 20}}); query.data.should.eql(data.slice(2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - limit', function(){ + it('find() - limit', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({age: {$gte: 20}}, {limit: 2}); query.data.should.eql(data.slice(1, 3)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - skip', function(){ + it('find() - skip', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({age: {$gte: 20}}, {skip: 1}); query.data.should.eql(data.slice(2)); @@ -243,32 +221,32 @@ describe('Query', function(){ query.data.should.eql(data.slice(2, 3)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - lean', function(){ + it('find() - lean', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({age: {$gt: 20}}, {lean: true}); query.should.be.a('array'); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $and', function(){ + it('find() - $and', function() { return User.insert([ {name: 'John', age: 20}, {name: 'John', age: 25}, {name: 'Jack', age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({ $and: [ {name: 'John'}, @@ -279,17 +257,17 @@ describe('Query', function(){ query.toArray().should.eql([data[1]]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $or', function(){ + it('find() - $or', function() { return User.insert([ {name: 'John', age: 20}, {name: 'John', age: 25}, {name: 'Jack', age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({ $or: [ {name: 'Jack'}, @@ -300,17 +278,17 @@ describe('Query', function(){ query.toArray().should.eql(data.slice(1)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $nor', function(){ + it('find() - $nor', function() { return User.insert([ {name: 'John', age: 20}, {name: 'John', age: 25}, {name: 'Jack', age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({ $nor: [ {name: 'Jack'}, @@ -321,17 +299,17 @@ describe('Query', function(){ query.toArray().should.eql([data[0]]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $not', function(){ + it('find() - $not', function() { return User.insert([ {name: 'John', age: 20}, {name: 'John', age: 25}, {name: 'Jack', age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({ $not: {name: 'John'} }); @@ -339,19 +317,19 @@ describe('Query', function(){ query.toArray().should.eql([data[2]]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('find() - $where', function(){ + it('find() - $where', function() { return User.insert([ {name: 'John', age: 20}, {name: 'John', age: 25}, {name: 'Jack', age: 30} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).find({ - $where: function(){ + $where: function() { return this.name === 'John'; } }); @@ -359,121 +337,119 @@ describe('Query', function(){ query.toArray().should.eql(data.slice(0, 2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('findOne()', function(){ + it('findOne()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { User.find({}).findOne({age: {$gt: 20}}).should.eql(data[2]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('findOne() - lean', function(){ + it('findOne() - lean', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { User.find({}).findOne({age: {$gt: 20}}, {lean: true})._id.should.eql(data[2]._id); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('sort()', function(){ + it('sort()', function() { return User.insert([ {age: 15}, {age: 35}, {age: 10} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).sort('age'); query.data[0].should.eql(data[2]); query.data[1].should.eql(data[0]); query.data[2].should.eql(data[1]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('sort() - descending', function(){ + it('sort() - descending', function() { return User.insert([ {age: 15}, {age: 35}, {age: 10} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).sort('age', -1); query.data[0].should.eql(data[1]); query.data[1].should.eql(data[0]); query.data[2].should.eql(data[2]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('sort() - multi', function(){ + it('sort() - multi', function() { return User.insert([ {age: 15, name: 'A'}, {age: 30, name: 'B'}, {age: 20, name: 'C'}, {age: 20, name: 'D'} - ]).then(function(data){ + ]).then(function(data) { var query = User.find({}).sort('age name'); query.data[0].should.eql(data[0]); query.data[1].should.eql(data[2]); query.data[2].should.eql(data[3]); query.data[3].should.eql(data[1]); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('map()', function(){ - return User.insert([ - {}, {}, {}, {}, {} - ]).then(function(data){ + it('map()', function() { + return User.insert(_.fill(Array(5), {})).then(function(data) { var num = 0; - var d1 = User.find({}).map(function(item, i){ + var d1 = User.find({}).map(function(item, i) { i.should.eql(num++); return item._id; }); - var d2 = data.map(function(item){ + var d2 = data.map(function(item) { return item._id; }); d1.should.eql(d2); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('reduce()', function(){ + it('reduce()', function() { return User.insert([ {name: 'A'}, {name: 'B'}, {name: 'C'} - ]).then(function(data){ + ]).then(function(data) { var num = 1; - var sum = User.find({}).reduce(function(sum, item, i){ + var sum = User.find({}).reduce(function(sum, item, i) { i.should.eql(num++); return {name: sum.name + item.name}; }); @@ -481,20 +457,20 @@ describe('Query', function(){ sum.name.should.eql('ABC'); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('reduce() - initial', function(){ + it('reduce() - initial', function() { return User.insert([ {name: 'A'}, {name: 'B'}, {name: 'C'} - ]).then(function(data){ + ]).then(function(data) { var num = 0; - var sum = User.find({}).reduce(function(sum, item, i){ + var sum = User.find({}).reduce(function(sum, item, i) { i.should.eql(num++); return sum + item.name; }, '_'); @@ -502,20 +478,20 @@ describe('Query', function(){ sum.should.eql('_ABC'); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('reduceRight()', function(){ + it('reduceRight()', function() { return User.insert([ {name: 'A'}, {name: 'B'}, {name: 'C'} - ]).then(function(data){ + ]).then(function(data) { var num = 1; - var sum = User.find({}).reduceRight(function(sum, item, i){ + var sum = User.find({}).reduceRight(function(sum, item, i) { i.should.eql(num--); return {name: sum.name + item.name}; }); @@ -523,20 +499,20 @@ describe('Query', function(){ sum.name.should.eql('CBA'); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('reduceRight() - initial', function(){ + it('reduceRight() - initial', function() { return User.insert([ {name: 'A'}, {name: 'B'}, {name: 'C'} - ]).then(function(data){ + ]).then(function(data) { var num = 2; - var sum = User.find({}).reduceRight(function(sum, item, i){ + var sum = User.find({}).reduceRight(function(sum, item, i) { i.should.eql(num--); return sum + item.name; }, '_'); @@ -544,21 +520,21 @@ describe('Query', function(){ sum.should.eql('_CBA'); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('filter()', function(){ + it('filter()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var num = 0; - var query = User.find({}).filter(function(data, i){ + var query = User.find({}).filter(function(data, i) { i.should.eql(num++); return data.age > 20; }); @@ -566,60 +542,60 @@ describe('Query', function(){ query.data.should.eql(data.slice(2)); return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('every()', function(){ + it('every()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var num = 0; - User.find({}).every(function(data, i){ + User.find({}).every(function(data, i) { i.should.eql(num++); return data.age; }).should.be.true; - User.find({}).every(function(data, i){ + User.find({}).every(function(data, i) { return data.age > 10; }).should.be.false; return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('some()', function(){ + it('some()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 40} - ]).then(function(data){ + ]).then(function(data) { var num = 0; - User.find({}).some(function(data, i){ + User.find({}).some(function(data, i) { return data.age > 10; }).should.be.true; - User.find({}).some(function(data, i){ + User.find({}).some(function(data, i) { i.should.eql(num++); return data.age < 0; }).should.be.false; return data; - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('update()', function(){ + it('update()', function() { return User.insert([ {age: 10}, {age: 20}, @@ -627,19 +603,19 @@ describe('Query', function(){ {age: 20}, {age: 40} ]).then(function(data) { - return User.find({age: 20}).update({name: 'A'}).then(function(updated){ + return User.find({age: 20}).update({name: 'A'}).then(function(updated) { updated[0]._id.should.eql(data[1]._id); updated[1]._id.should.eql(data[3]._id); updated[0].name.should.eql('A'); updated[1].name.should.eql('A'); return data; }); - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('replace()', function(){ + it('replace()', function() { return User.insert([ {age: 10}, {age: 20}, @@ -647,49 +623,49 @@ describe('Query', function(){ {age: 20}, {age: 40} ]).then(function(data) { - return User.find({age: 20}).replace({name: 'A'}).then(function(updated){ + return User.find({age: 20}).replace({name: 'A'}).then(function(updated) { updated[0]._id.should.eql(data[1]._id); updated[1]._id.should.eql(data[3]._id); updated[0].name.should.eql('A'); updated[1].name.should.eql('A'); return data; }); - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('remove()', function(){ + it('remove()', function() { return User.insert([ {age: 10}, {age: 20}, {age: 30}, {age: 20}, {age: 40} - ]).then(function(data){ - return User.find({age: 20}).remove().then(function(removed){ + ]).then(function(data) { + return User.find({age: 20}).remove().then(function(removed) { should.not.exist(User.findById(data[1]._id)); should.not.exist(User.findById(data[3]._id)); return [data[0], data[2], data[4]]; }); - }).map(function(item){ + }).map(function(item) { return User.removeById(item._id); }); }); - it('populate() - object', function(){ + it('populate() - object', function() { var user, comment; - return User.insert({}).then(function(user_){ + return User.insert({}).then(function(user_) { user = user_; return Comment.insert({ author: user._id }); - }).then(function(comment_){ + }).then(function(comment_) { comment = comment_; return Comment.find({}).populate('author'); - }).then(function(result){ + }).then(function(result) { result.first().author.should.eql(user); return Promise.all([ @@ -699,7 +675,7 @@ describe('Query', function(){ }); }); - it('populate() - array', function(){ + it('populate() - array', function() { var comments, user; return Comment.insert([ @@ -707,16 +683,16 @@ describe('Query', function(){ {content: 'bar'}, {content: 'baz'}, {content: 'ha'} - ]).then(function(comments_){ + ]).then(function(comments_) { comments = comments_; return User.insert({ comments: _.map(comments, '_id') }); - }).then(function(user_){ + }).then(function(user_) { user = user_; return User.populate('comments'); - }).then(function(result){ + }).then(function(result) { result.first().comments.toArray().should.eql(comments); return Promise.all([ @@ -728,4 +704,4 @@ describe('Query', function(){ ]); }); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/queue.js b/test/scripts/queue.js index 219c6ad7..cd775eef 100644 --- a/test/scripts/queue.js +++ b/test/scripts/queue.js @@ -1,35 +1,38 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var Promise = require('bluebird'); var sinon = require('sinon'); -function wait(ms){ - return new Promise(function(resolve, reject){ - setTimeout(function(){ +function wait(ms) { + return new Promise(function(resolve, reject) { + setTimeout(function() { resolve(); }, ms); }); } -describe('Queue', function(){ +describe('Queue', function() { var Queue = require('../../lib/queue'); var queue = new Queue(); - it('push()', function(){ - var fn1 = sinon.spy(function(){ - return wait(30).then(function(){ + it('push()', function() { + var fn2; + var fn1 = sinon.spy(function() { + return wait(30).then(function() { fn2.called.should.be.false; return 'foo'; }); }); - var fn2 = sinon.spy(function(){ + fn2 = sinon.spy(function() { return 'bar'; }); return Promise.all([ queue.push(fn1), queue.push(fn2) - ]).then(function(result){ + ]).then(function(result) { queue.tasks.length.should.eql(0); queue.pendingTasks.should.eql(0); fn1.calledOnce.should.be.true; @@ -38,24 +41,25 @@ describe('Queue', function(){ }); }); - it('push() - error handling', function(){ - var fn1 = sinon.spy(function(){ + it('push() - error handling', function() { + var fn1 = sinon.spy(function() { throw new Error('WOW!'); }); - var fn2 = sinon.spy(function(){ + var fn2 = sinon.spy(function() { return 'bar'; }); return Promise.all([ - queue.push(fn1).catch(function(err){ + queue.push(fn1).catch(function(err) { err.should.have.property('message', 'WOW!'); }), + queue.push(fn2) - ]).then(function(result){ + ]).then(function(result) { fn1.calledOnce.should.be.true; fn2.calledOnce.should.be.true; result.should.eql([undefined, 'bar']); }); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/schema.js b/test/scripts/schema.js index c8cbae6e..203c83b7 100644 --- a/test/scripts/schema.js +++ b/test/scripts/schema.js @@ -1,10 +1,12 @@ -var should = require('chai').should(); +'use strict'; -describe('Schema', function(){ +var should = require('chai').should(); // eslint-disable-line + +describe('Schema', function() { var Database = require('../..'); var Schema = Database.Schema; - it('add()', function(){ + it('add()', function() { var schema = new Schema(); schema.add({ @@ -65,113 +67,120 @@ describe('Schema', function(){ schema.paths.id.options.required.should.be.true; }); - it('virtual() - without getter', function(){ + it('virtual() - without getter', function() { var schema = new Schema(); schema.virtual('test'); schema.paths.test.should.be.an.instanceOf(Schema.Types.Virtual); }); - it('virtual() - with getter', function(){ + it('virtual() - with getter', function() { var schema = new Schema(); - schema.virtual('test', function(){}); + schema.virtual('test', function() {}); + schema.paths.test.should.be .an.instanceOf(Schema.Types.Virtual) .have.property('getter'); }); - it('pre()', function(){ + it('pre()', function() { var schema = new Schema(); // save - schema.pre('save', function(){}); + schema.pre('save', function() {}); + schema.hooks.pre.save.should.have.length(1); // remove - schema.pre('remove', function(){}); + schema.pre('remove', function() {}); + schema.hooks.pre.remove.should.have.length(1); // incompatible type try { - schema.pre('wtf', function(){}); - } catch (err){ + schema.pre('wtf', function() {}); + } catch (err) { err.should.eql(new TypeError('Hook type must be `save` or `remove`!')); } // hook is not a function try { schema.pre('save'); - } catch (err){ + } catch (err) { err.should.eql(new TypeError('Hook must be a function!')); } }); - it('post()', function(){ + it('post()', function() { var schema = new Schema(); // save - schema.post('save', function(){}); + schema.post('save', function() {}); + schema.hooks.post.save.should.have.length(1); // remove - schema.post('remove', function(){}); + schema.post('remove', function() {}); + schema.hooks.post.remove.should.have.length(1); // incompatible type try { - schema.post('wtf', function(){}); - } catch (err){ + schema.post('wtf', function() {}); + } catch (err) { err.should.eql(new TypeError('Hook type must be `save` or `remove`!')); } // hook is not a function try { schema.post('save'); - } catch (err){ + } catch (err) { err.should.eql(new TypeError('Hook must be a function!')); } }); - it('method()', function(){ + it('method()', function() { var schema = new Schema(); - schema.method('test', function(){}); + schema.method('test', function() {}); + schema.methods.test.should.exist; // without name try { schema.method(); - } catch (err){ + } catch (err) { err.should.eql(new TypeError('Method name is required!')); } // without function try { schema.method('wtf'); - } catch (err){ + } catch (err) { err.should.eql(new TypeError('Instance method must be a function!')); } }); - it('static()', function(){ + it('static()', function() { var schema = new Schema(); - schema.static('test', function(){}); + schema.static('test', function() {}); + schema.statics.test.should.exist; // without name try { schema.static(); - } catch (err){ + } catch (err) { err.should.eql(new TypeError('Method name is required!')); } // without function try { schema.sttic('wtf'); - } catch (err){ + } catch (err) { err.should.eql(new TypeError('Static method must be a function!')); } }); -}); \ No newline at end of file +}); diff --git a/test/scripts/schematype.js b/test/scripts/schematype.js index ff4c268b..5d1f8412 100644 --- a/test/scripts/schematype.js +++ b/test/scripts/schematype.js @@ -1,50 +1,52 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../lib/error/validation'); -describe('SchemaType', function(){ +describe('SchemaType', function() { var SchemaType = require('../../lib/schematype'); var type = new SchemaType('test'); - it('cast()', function(){ + it('cast()', function() { type.cast(123).should.eql(123); }); - it('cast() - default', function(){ + it('cast() - default', function() { var type = new SchemaType('test', {default: 'foo'}); type.cast().should.eql('foo'); }); - it('validate()', function(){ + it('validate()', function() { type.validate(123).should.eql(123); }); - it('validate() - required', function(){ + it('validate() - required', function() { var type = new SchemaType('test', {required: true}); type.validate().should.be .instanceOf(ValidationError) .property('message', '`test` is required!'); }); - it('compare()', function(){ + it('compare()', function() { type.compare(2, 1).should.eql(1); type.compare(1, 2).should.eql(-1); type.compare(1, 1).should.eql(0); }); - it('parse()', function(){ + it('parse()', function() { type.parse(123).should.eql(123); }); - it('value()', function(){ + it('value()', function() { type.value(123).should.eql(123); }); - it('match()', function(){ + it('match()', function() { type.match(1, 1).should.be.true; type.match(1, '1').should.be.false; }); - it('q$exist', function(){ + it('q$exist', function() { // array type.q$exist(['foo'], true).should.be.true; type.q$exist([], true).should.be.true; @@ -82,57 +84,57 @@ describe('SchemaType', function(){ type.q$exist(undefined, false).should.be.true; }); - it('q$ne', function(){ + it('q$ne', function() { type.q$ne(1, 1).should.be.false; type.q$ne(1, '1').should.be.true; }); - it('q$lt', function(){ + it('q$lt', function() { type.q$lt(1, 2).should.be.true; type.q$lt(1, 1).should.be.false; type.q$lt(1, 0).should.be.false; }); - it('q$lte', function(){ + it('q$lte', function() { type.q$lte(1, 2).should.be.true; type.q$lte(1, 1).should.be.true; type.q$lte(1, 0).should.be.false; }); - it('q$gt', function(){ + it('q$gt', function() { type.q$gt(1, 2).should.be.false; type.q$gt(1, 1).should.be.false; type.q$gt(1, 0).should.be.true; }); - it('q$gte', function(){ + it('q$gte', function() { type.q$gte(1, 2).should.be.false; type.q$gte(1, 1).should.be.true; type.q$gte(1, 0).should.be.true; }); - it('q$in', function(){ + it('q$in', function() { type.q$in(1, [0, 1, 2]).should.be.true; type.q$in(1, ['0', '1', '2']).should.be.false; }); - it('q$nin', function(){ + it('q$nin', function() { type.q$nin(1, [0, 2, 4]).should.be.true; type.q$nin(1, [0, 1, 2]).should.be.false; }); - it('u$set', function(){ + it('u$set', function() { type.u$set(1, 1).should.eql(1); }); - it('u$unset', function(){ + it('u$unset', function() { should.not.exist(type.u$unset(1, true)); type.u$unset(1, false).should.eql(1); }); - it('u$rename', function(){ + it('u$rename', function() { var obj = {a: 1}; should.not.exist(type.u$rename(1, 'b', obj)); obj.b.should.eql(1); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/array.js b/test/scripts/types/array.js index ed49c167..8b16d03f 100644 --- a/test/scripts/types/array.js +++ b/test/scripts/types/array.js @@ -1,37 +1,39 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../../lib/error/validation'); -describe('SchemaTypeArray', function(){ +describe('SchemaTypeArray', function() { var SchemaTypeArray = require('../../../lib/types/array'); var SchemaTypeString = require('../../../lib/types/string'); var SchemaTypeDate = require('../../../lib/types/date'); var SchemaTypeBoolean = require('../../../lib/types/boolean'); var type = new SchemaTypeArray('test'); - it('cast()', function(){ + it('cast()', function() { type.cast('foo').should.eql(['foo']); type.cast([]).should.eql([]); type.cast([1, 2, 3]).should.eql([1, 2, 3]); type.cast().should.eql([]); }); - it('cast() - default', function(){ + it('cast() - default', function() { var type = new SchemaTypeArray('test', {default: [1, 2, 3]}); type.cast().should.eql([1, 2, 3]); }); - it('cast() - child', function(){ + it('cast() - child', function() { var type = new SchemaTypeArray('test', {child: new SchemaTypeString()}); type.cast([1, 2, 3]).should.eql(['1', '2', '3']); }); - function shouldThrowError(value){ + function shouldThrowError(value) { type.validate(value).should.be .instanceOf(ValidationError) .property('message', '`' + value + '` is not an array!'); } - it('validate()', function(){ + it('validate()', function() { type.validate([]).should.eql([]); type.validate([1, 2, 3]).should.eql([1, 2, 3]); shouldThrowError(''); @@ -42,7 +44,7 @@ describe('SchemaTypeArray', function(){ shouldThrowError(true); }); - it('validate() - required', function(){ + it('validate() - required', function() { var type = new SchemaTypeArray('test', {required: true}); type.validate().should.be @@ -50,7 +52,7 @@ describe('SchemaTypeArray', function(){ .property('message', '`test` is required!'); }); - it('validate() - child', function(){ + it('validate() - child', function() { var type = new SchemaTypeArray('test', {child: new SchemaTypeString()}); type.validate([1, 2, 3]).should.be @@ -58,7 +60,7 @@ describe('SchemaTypeArray', function(){ .property('message', '`1` is not a string!'); }); - it('compare()', function(){ + it('compare()', function() { type.compare([1, 2, 3], [1, 2, 4]).should.eql(-1); type.compare([1, 2, 3], [1, 2, 3]).should.eql(0); type.compare([1, 2, 3], [1, 2, 2]).should.eql(1); @@ -68,46 +70,46 @@ describe('SchemaTypeArray', function(){ type.compare().should.eql(0); }); - it('compare() - child', function(){ + it('compare() - child', function() { var type = new SchemaTypeArray('test', {child: new SchemaTypeDate()}); type.compare([new Date(1e8), new Date(1e8 + 1)], [new Date(1e8), new Date(1e8 + 2)]) .should.eql(-1); }); - it('parse()', function(){ + it('parse()', function() { type.parse([1, 2, 3]).should.eql([1, 2, 3]); should.not.exist(type.parse()); }); - it('parse() - child', function(){ + it('parse() - child', function() { var type = new SchemaTypeArray('test', {child: new SchemaTypeBoolean()}); type.parse([0, 1, 0]).should.eql([false, true, false]); }); - it('value()', function(){ + it('value()', function() { type.value([1, 2, 3]).should.eql([1, 2, 3]); should.not.exist(type.value()); }); - it('value() - child', function(){ + it('value() - child', function() { var type = new SchemaTypeArray('test', {child: new SchemaTypeBoolean()}); type.value([true, false, true]).should.eql([1, 0, 1]); }); - it('match()', function(){ + it('match()', function() { type.match([1, 2, 3], [1, 2, 3]).should.be.true; type.match([1, 2, 3], ['1', '2', '3']).should.be.false; type.match([1, 2, 3], [1, 2, 3, 4]).should.be.false; type.match(undefined, []).should.be.false; }); - it('match() - child', function(){ + it('match() - child', function() { var type = new SchemaTypeArray('test', {child: new SchemaTypeDate()}); type.match([new Date(2014, 1, 1)], [new Date(2014, 1, 1)]).should.be.true; type.match([new Date(2014, 1, 2)], [new Date(2014, 1, 1)]).should.be.false; }); - it('q$size()', function(){ + it('q$size()', function() { type.q$size([1, 2, 3], 3).should.be.true; type.q$size([1, 2], 3).should.be.false; type.q$size([], 0).should.be.true; @@ -115,46 +117,46 @@ describe('SchemaTypeArray', function(){ type.q$size(undefined, 3).should.be.false; }); - it('q$in()', function(){ + it('q$in()', function() { type.q$in([1, 2, 3], [1, 4]).should.be.true; type.q$in([1, 2, 3], [4, 5]).should.be.false; type.q$in(undefined, [1, 2]).should.be.false; }); - it('q$nin()', function(){ + it('q$nin()', function() { type.q$nin([1, 2, 3], [1, 4]).should.be.false; type.q$nin([1, 2, 3], [4, 5]).should.be.true; type.q$nin(undefined, [1, 2]).should.be.true; }); - it('q$all()', function(){ + it('q$all()', function() { type.q$all([1, 2, 3], [1, 2]).should.be.true; type.q$all([1, 2, 3], [1, 4]).should.be.false; type.q$all([1, 2, 3], [4, 5, 6]).should.be.false; type.q$all(undefined, [1, 2]).should.be.false; }); - it('u$push()', function(){ + it('u$push()', function() { type.u$push([1, 2, 3], 4).should.eql([1, 2, 3, 4]); type.u$push([1, 2, 3], [4, 5]).should.eql([1, 2, 3, 4, 5]); type.u$push(undefined, 4).should.eql([4]); type.u$push(undefined, [4, 5]).should.eql([4, 5]); }); - it('u$unshift()', function(){ + it('u$unshift()', function() { type.u$unshift([1, 2, 3], 0).should.eql([0, 1, 2, 3]); type.u$unshift([1, 2, 3], [-1, 0]).should.eql([-1, 0, 1, 2, 3]); type.u$unshift(undefined, 0).should.eql([0]); type.u$unshift(undefined, [0, 1]).should.eql([0, 1]); }); - it('u$pull()', function(){ + it('u$pull()', function() { type.u$pull([1, 2, 3, 3, 4], 3).should.eql([1, 2, 4]); type.u$pull([1, 1, 2, 3, 3], [1, 3]).should.eql([2]); should.not.exist(type.u$pull(undefined, 1)); }); - it('u$shift()', function(){ + it('u$shift()', function() { type.u$shift([1, 2, 3], true).should.eql([2, 3]); type.u$shift([1, 2, 3], 2).should.eql([3]); type.u$shift([1, 2, 3], false).should.eql([1, 2, 3]); @@ -163,7 +165,7 @@ describe('SchemaTypeArray', function(){ should.not.exist(type.u$shift(undefined, true)); }); - it('u$pop()', function(){ + it('u$pop()', function() { type.u$pop([1, 2, 3], true).should.eql([1, 2]); type.u$pop([1, 2, 3], 2).should.eql([1]); type.u$pop([1, 2, 3], false).should.eql([1, 2, 3]); @@ -172,7 +174,7 @@ describe('SchemaTypeArray', function(){ should.not.exist(type.u$pop(undefined, true)); }); - it('u$addToSet()', function(){ + it('u$addToSet()', function() { type.u$addToSet([1, 2, 3], 4).should.eql([1, 2, 3, 4]); type.u$addToSet([1, 2, 3], 2).should.eql([1, 2, 3]); type.u$addToSet([1, 2, 3], [4, 5]).should.eql([1, 2, 3, 4, 5]); @@ -180,4 +182,4 @@ describe('SchemaTypeArray', function(){ type.u$addToSet(undefined, 1).should.eql([1]); type.u$addToSet(undefined, [1, 2, 3]).should.eql([1, 2, 3]); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/boolean.js b/test/scripts/types/boolean.js index 25e7f1d9..26e06a2d 100644 --- a/test/scripts/types/boolean.js +++ b/test/scripts/types/boolean.js @@ -1,11 +1,13 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../../lib/error/validation'); -describe('SchemaTypeBoolean', function(){ +describe('SchemaTypeBoolean', function() { var SchemaTypeBoolean = require('../../../lib/types/boolean'); var type = new SchemaTypeBoolean('test'); - it('cast()', function(){ + it('cast()', function() { type.cast(true).should.eql(true); type.cast(false).should.eql(false); @@ -20,18 +22,18 @@ describe('SchemaTypeBoolean', function(){ type.cast('foo').should.eql(true); }); - it('cast() - default', function(){ + it('cast() - default', function() { var type = new SchemaTypeBoolean('test', {default: true}); type.cast().should.eql(true); }); - function shouldThrowError(value){ + function shouldThrowError(value) { type.validate(value).should.be .instanceOf(ValidationError) .property('message', '`' + value + '` is not a boolean!'); } - it('validate()', function(){ + it('validate()', function() { type.validate(true).should.eql(true); type.validate(false).should.eql(false); shouldThrowError(1); @@ -42,20 +44,20 @@ describe('SchemaTypeBoolean', function(){ shouldThrowError({}); }); - it('validate() - required', function(){ + it('validate() - required', function() { var type = new SchemaTypeBoolean('test', {required: true}); type.validate().should.be .instanceOf(ValidationError) .property('message', '`test` is required!'); }); - it('parse()', function(){ + it('parse()', function() { type.parse(1).should.eql(true); type.parse(0).should.eql(false); }); - it('value()', function(){ + it('value()', function() { type.value(true).should.eql(1); type.value(false).should.eql(0); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/cuid.js b/test/scripts/types/cuid.js index 3b612ca6..977523a4 100644 --- a/test/scripts/types/cuid.js +++ b/test/scripts/types/cuid.js @@ -1,24 +1,26 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../../lib/error/validation'); -describe('SchemaTypeCUID', function(){ +describe('SchemaTypeCUID', function() { var SchemaTypeCUID = require('../../../lib/types/cuid'); var type = new SchemaTypeCUID('test'); - it('cast()', function(){ + it('cast()', function() { type.cast('foo').should.eql('foo'); should.not.exist(type.cast()); }); - it('cast() - required', function(){ + it('cast() - required', function() { var type = new SchemaTypeCUID('test', {required: true}); type.cast().should.exist; }); - it('validate()', function(){ + it('validate()', function() { type.validate('ch72gsb320000udocl363eofy').should.eql('ch72gsb320000udocl363eofy'); type.validate('foo').should.be .instanceOf(ValidationError) .property('message', '`foo` is not a valid CUID'); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/date.js b/test/scripts/types/date.js index 606b8f9b..1cce66c3 100644 --- a/test/scripts/types/date.js +++ b/test/scripts/types/date.js @@ -1,30 +1,32 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../../lib/error/validation'); -describe('SchemaTypeDate', function(){ +describe('SchemaTypeDate', function() { var SchemaTypeDate = require('../../../lib/types/date'); var type = new SchemaTypeDate('test'); - it('cast()', function(){ + it('cast()', function() { type.cast(new Date(2014, 1, 1)).should.eql(new Date(2014, 1, 1)); type.cast(1e8).should.eql(new Date(1e8)); type.cast('2014-11-03T07:45:41.237Z').should.eql(new Date('2014-11-03T07:45:41.237Z')); }); - it('cast() - default', function(){ + it('cast() - default', function() { var date = new Date(); var type = new SchemaTypeDate('test', {default: date}); type.cast().should.eql(date); }); - function shouldThrowError(value){ + function shouldThrowError(value) { type.validate(value).should.be .instanceOf(ValidationError) .property('message', '`' + value + '` is not a valid date!'); } - it('validate()', function(){ + it('validate()', function() { type.validate(new Date(2014, 1, 1)).should.eql(new Date(2014, 1, 1)); shouldThrowError(1); shouldThrowError('foo'); @@ -34,20 +36,20 @@ describe('SchemaTypeDate', function(){ shouldThrowError(new Date('foo')); }); - it('validate() - required', function(){ + it('validate() - required', function() { var type = new SchemaTypeDate('test', {required: true}); type.validate().should.be .instanceOf(ValidationError) .property('message', '`test` is required!'); }); - it('match()', function(){ + it('match()', function() { type.match(new Date(2014, 1, 1), new Date(2014, 1, 1)).should.be.true; type.match(new Date(2014, 1, 1), new Date(2014, 1, 2)).should.be.false; type.match(undefined, new Date()).should.be.false; }); - it('compare()', function(){ + it('compare()', function() { type.compare(new Date(2014, 1, 3), new Date(2014, 1, 2)).should.gt(0); type.compare(new Date(2014, 1, 1), new Date(2014, 1, 2)).should.lt(0); type.compare(new Date(2014, 1, 2), new Date(2014, 1, 2)).should.eql(0); @@ -56,41 +58,41 @@ describe('SchemaTypeDate', function(){ type.compare().should.eql(0); }); - it('parse()', function(){ + it('parse()', function() { type.parse('2014-11-03T07:45:41.237Z').should.eql(new Date('2014-11-03T07:45:41.237Z')); should.not.exist(type.parse()); }); - it('value()', function(){ + it('value()', function() { type.value(new Date('2014-11-03T07:45:41.237Z')).should.eql('2014-11-03T07:45:41.237Z'); should.not.exist(type.value()); }); - it('q$day()', function(){ + it('q$day()', function() { type.q$day(new Date(2014, 1, 1), 1).should.be.true; type.q$day(new Date(2014, 1, 1), 5).should.be.false; type.q$day(undefined, 1).should.be.false; }); - it('q$month()', function(){ + it('q$month()', function() { type.q$month(new Date(2014, 1, 1), 1).should.be.true; type.q$month(new Date(2014, 1, 1), 5).should.be.false; type.q$month(undefined, 1).should.be.false; }); - it('q$year()', function(){ + it('q$year()', function() { type.q$year(new Date(2014, 1, 1), 2014).should.be.true; type.q$year(new Date(2014, 1, 1), 1999).should.be.false; type.q$year(undefined, 2014).should.be.false; }); - it('u$inc()', function(){ + it('u$inc()', function() { type.u$inc(new Date(1e8), 1).should.eql(new Date(1e8 + 1)); should.not.exist(undefined, 1); }); - it('u$dec()', function(){ + it('u$dec()', function() { type.u$dec(new Date(1e8), 1).should.eql(new Date(1e8 - 1)); should.not.exist(undefined, 1); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/enum.js b/test/scripts/types/enum.js index 7c5340c9..bbe31a9a 100644 --- a/test/scripts/types/enum.js +++ b/test/scripts/types/enum.js @@ -1,10 +1,12 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../../lib/error/validation'); -describe('SchemaTypeEnum', function(){ +describe('SchemaTypeEnum', function() { var SchemaTypeEnum = require('../../../lib/types/enum'); - it('validate()', function(){ + it('validate()', function() { var type = new SchemaTypeEnum('test', {elements: ['foo', 'bar', 'baz']}); type.validate('foo').should.eql('foo'); @@ -13,10 +15,10 @@ describe('SchemaTypeEnum', function(){ .property('message', 'The value must be one of foo, bar, baz'); }); - it('validate() - required', function(){ + it('validate() - required', function() { var type = new SchemaTypeEnum('test', {required: true}); type.validate().should.be .instanceOf(ValidationError) .property('message', '`test` is required!'); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/integer.js b/test/scripts/types/integer.js index 009fff81..4099b4a6 100644 --- a/test/scripts/types/integer.js +++ b/test/scripts/types/integer.js @@ -1,11 +1,13 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../../lib/error/validation'); -describe('SchemaTypeInteger', function(){ +describe('SchemaTypeInteger', function() { var SchemaTypeInteger = require('../../../lib/types/integer'); var type = new SchemaTypeInteger('test'); - it('cast()', function(){ + it('cast()', function() { type.cast(0).should.eql(0); type.cast(3.14).should.eql(3); type.cast('0').should.eql(0); @@ -15,18 +17,18 @@ describe('SchemaTypeInteger', function(){ type.cast(false).should.eql(0); }); - it('cast() - default', function(){ + it('cast() - default', function() { var type = new SchemaTypeInteger('test', {default: 3}); type.cast().should.eql(3); }); - function shouldThrowError(value){ + function shouldThrowError(value) { type.validate(value).should.be .instanceOf(ValidationError) .property('message', '`' + value + '` is not a number!'); } - it('validate()', function(){ + it('validate()', function() { type.validate(1).should.eql(1); type.validate(0).should.eql(0); type.validate(3.14).should.be @@ -39,10 +41,10 @@ describe('SchemaTypeInteger', function(){ shouldThrowError({}); }); - it('validate() - required', function(){ + it('validate() - required', function() { var type = new SchemaTypeInteger('test', {required: true}); type.validate().should.be .instanceOf(ValidationError) .property('message', '`test` is required!'); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/number.js b/test/scripts/types/number.js index af6f1ce0..30d8ff16 100644 --- a/test/scripts/types/number.js +++ b/test/scripts/types/number.js @@ -1,11 +1,13 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../../lib/error/validation'); -describe('SchemaTypeNumber', function(){ +describe('SchemaTypeNumber', function() { var SchemaTypeNumber = require('../../../lib/types/number'); var type = new SchemaTypeNumber('type'); - it('cast()', function(){ + it('cast()', function() { type.cast(0).should.eql(0); type.cast(1).should.eql(1); type.cast('0').should.eql(0); @@ -14,18 +16,18 @@ describe('SchemaTypeNumber', function(){ type.cast(false).should.eql(0); }); - it('cast() - default', function(){ + it('cast() - default', function() { var type = new SchemaTypeNumber('type', {default: 42}); type.cast().should.eql(42); }); - function shouldThrowError(value){ + function shouldThrowError(value) { type.validate(value).should.be .instanceOf(ValidationError) .property('message', '`' + value + '` is not a number!'); } - it('validate()', function(){ + it('validate()', function() { type.validate(1).should.eql(1); type.validate(0).should.eql(0); shouldThrowError(NaN); @@ -36,45 +38,45 @@ describe('SchemaTypeNumber', function(){ shouldThrowError({}); }); - it('validate() - required', function(){ + it('validate() - required', function() { var type = new SchemaTypeNumber('test', {required: true}); type.validate().should.be .instanceOf(ValidationError) .property('message', '`test` is required!'); }); - it('u$inc()', function(){ + it('u$inc()', function() { type.u$inc(2, 3).should.eql(5); type.u$inc(undefined, 3).should.eql(3); }); - it('u$dec()', function(){ + it('u$dec()', function() { type.u$dec(2, 3).should.eql(-1); type.u$dec(undefined, 3).should.eql(-3); }); - it('u$mul()', function(){ + it('u$mul()', function() { type.u$mul(2, 3).should.eql(6); type.u$mul(undefined, 3).should.eql(0); }); - it('u$div()', function(){ + it('u$div()', function() { type.u$div(10, 5).should.eql(2); type.u$div(undefined, 5).should.eql(0); }); - it('u$mod()', function(){ + it('u$mod()', function() { type.u$mod(13, 5).should.eql(3); type.u$mod(undefined, 5).should.eql(0); }); - it('u$max()', function(){ + it('u$max()', function() { type.u$max(20, 50).should.eql(50); type.u$max(70, 50).should.eql(70); }); - it('u$min()', function(){ + it('u$min()', function() { type.u$min(30, 20).should.eql(20); type.u$min(10, 20).should.eql(10); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/object.js b/test/scripts/types/object.js index c127d9af..6ca913a0 100644 --- a/test/scripts/types/object.js +++ b/test/scripts/types/object.js @@ -1,10 +1,12 @@ -var should = require('chai').should(); +'use strict'; -describe('SchemaTypeObject', function(){ - var SchemaTypeObject = require('../../../lib/types/object'), - type = new SchemaTypeObject('test'); +var should = require('chai').should(); // eslint-disable-line - it('cast() - default', function(){ +describe('SchemaTypeObject', function() { + var SchemaTypeObject = require('../../../lib/types/object'); + var type = new SchemaTypeObject('test'); + + it('cast() - default', function() { type.cast().should.eql({}); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/string.js b/test/scripts/types/string.js index 2a25c226..6cb2eedb 100644 --- a/test/scripts/types/string.js +++ b/test/scripts/types/string.js @@ -1,33 +1,37 @@ -var should = require('chai').should(); +'use strict'; + +var should = require('chai').should(); // eslint-disable-line var ValidationError = require('../../../lib/error/validation'); -describe('SchemaTypeString', function(){ +describe('SchemaTypeString', function() { var SchemaTypeString = require('../../../lib/types/string'); var type = new SchemaTypeString('test'); - it('cast()', function(){ + it('cast()', function() { type.cast('foo').should.eql('foo'); type.cast(42).should.eql('42'); type.cast(true).should.eql('true'); type.cast([1, 2, 3]).should.eql('1,2,3'); type.cast({}).should.eql('[object Object]'); type.cast({ - toString: function(){return 'baz'} + toString: function() { + return 'baz'; + } }).should.eql('baz'); }); - it('cast() - default', function(){ + it('cast() - default', function() { var type = new SchemaTypeString('test', {default: 'foo'}); type.cast().should.eql('foo'); }); - function shouldThrowError(value){ + function shouldThrowError(value) { type.validate(value).should.be .instanceOf(ValidationError) .property('message', '`' + value + '` is not a string!'); } - it('validate()', function(){ + it('validate()', function() { type.validate('foo').should.eql('foo'); type.validate('').should.eql(''); shouldThrowError(1); @@ -38,25 +42,25 @@ describe('SchemaTypeString', function(){ shouldThrowError({}); }); - it('validate() - required', function(){ + it('validate() - required', function() { var type = new SchemaTypeString('test', {required: true}); type.validate().should.be .instanceOf(ValidationError) .property('message', '`test` is required!'); }); - it('match()', function(){ + it('match()', function() { type.match('foo', 'foo').should.be.true; type.match('foo', 'bar').should.be.false; }); - it('match() - RegExp', function(){ + it('match() - RegExp', function() { type.match('foo', /^f/).should.be.true; type.match('bar', /^f/).should.be.false; type.match(undefined, /^f/).should.be.false; }); - it('q$in()', function(){ + it('q$in()', function() { type.q$in('foo', ['foo', 'bar', 'baz']).should.be.true; type.q$in('wat', ['foo', 'bar', 'baz']).should.be.false; type.q$in(undefined, ['foo', 'bar', 'baz']).should.be.false; @@ -64,7 +68,7 @@ describe('SchemaTypeString', function(){ type.q$in('bar', [/^f/, /^g/]).should.be.false; }); - it('q$nin()', function(){ + it('q$nin()', function() { type.q$nin('foo', ['foo', 'bar', 'baz']).should.be.false; type.q$nin('wat', ['foo', 'bar', 'baz']).should.be.true; type.q$nin(undefined, ['foo', 'bar', 'baz']).should.be.true; @@ -72,10 +76,10 @@ describe('SchemaTypeString', function(){ type.q$nin('bar', [/^f/, /^g/]).should.be.true; }); - it('q$length()', function(){ + it('q$length()', function() { type.q$length('foo', 3).should.be.true; type.q$length('foo', 5).should.be.false; type.q$length(undefined, 3).should.be.false; type.q$length(undefined, 0).should.be.true; }); -}); \ No newline at end of file +}); diff --git a/test/scripts/types/virtual.js b/test/scripts/types/virtual.js index 710fc766..b078f0b0 100644 --- a/test/scripts/types/virtual.js +++ b/test/scripts/types/virtual.js @@ -1,11 +1,13 @@ -var should = require('chai').should(); +'use strict'; -describe('SchemaTypeVirtual', function(){ +var should = require('chai').should(); // eslint-disable-line + +describe('SchemaTypeVirtual', function() { var SchemaTypeVirtual = require('../../../lib/types/virtual'); var type = new SchemaTypeVirtual('test'); - it('get()', function(){ - var getter = function(){ + it('get()', function() { + var getter = function() { return 'foo'; }; @@ -13,18 +15,18 @@ describe('SchemaTypeVirtual', function(){ type.getter.should.eql(getter); }); - it('get() - type check', function(){ + it('get() - type check', function() { try { type.get(123); - } catch (err){ + } catch (err) { err.should.be .instanceOf(TypeError) .property('message', 'Getter must be a function!'); } }); - it('set()', function(){ - var setter = function(){ + it('set()', function() { + var setter = function() { this.foo = 'foo'; }; @@ -32,20 +34,20 @@ describe('SchemaTypeVirtual', function(){ type.setter.should.eql(setter); }); - it('set() - type check', function(){ + it('set() - type check', function() { try { type.set(123); - } catch (err){ + } catch (err) { err.should.be .instanceOf(TypeError) .property('message', 'Setter must be a function!'); } }); - it('cast()', function(){ + it('cast()', function() { var obj = {name: 'foo'}; - type.get(function(){ + type.get(function() { return this.name.toUpperCase(); }); @@ -53,14 +55,14 @@ describe('SchemaTypeVirtual', function(){ obj.test.should.eql('FOO'); }); - it('validate()', function(){ + it('validate()', function() { var obj = {}; - type.set(function(value){ + type.set(function(value) { this.name = value.toLowerCase(); }); type.validate('FOO', obj); obj.name.should.eql('foo'); }); -}); \ No newline at end of file +}); diff --git a/test/scripts/util.js b/test/scripts/util.js index 84a798ca..a657a518 100644 --- a/test/scripts/util.js +++ b/test/scripts/util.js @@ -1,9 +1,11 @@ -var should = require('chai').should(); +'use strict'; -describe('util', function(){ +var should = require('chai').should(); // eslint-disable-line + +describe('util', function() { var util = require('../../lib/util'); - it('getProp()', function(){ + it('getProp()', function() { var obj = { a: { b: 1 @@ -21,23 +23,23 @@ describe('util', function(){ util.getProp(obj, 'd.e.f').should.eql(obj.d.e.f); }); - it('getProp() - obj must be an object', function(){ + it('getProp() - obj must be an object', function() { try { util.getProp(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'obj must be an object!'); } }); - it('getProp() - key is required', function(){ + it('getProp() - key is required', function() { try { util.getProp({}); - } catch (err){ + } catch (err) { err.should.have.property('message', 'key is required!'); } }); - it('setProp()', function(){ + it('setProp()', function() { var obj = { a: { b: 1 @@ -60,23 +62,23 @@ describe('util', function(){ obj.d.e.f.should.eql('haha'); }); - it('setProp() - obj must be an object', function(){ + it('setProp() - obj must be an object', function() { try { util.setProp(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'obj must be an object!'); } }); - it('setProp() - key is required', function(){ + it('setProp() - key is required', function() { try { util.setProp({}); - } catch (err){ + } catch (err) { err.should.have.property('message', 'key is required!'); } }); - it('delProp()', function(){ + it('delProp()', function() { var obj = { a: { b: 1 @@ -99,23 +101,23 @@ describe('util', function(){ should.not.exist(obj.d.e.f); }); - it('delProp() - obj must be an object', function(){ + it('delProp() - obj must be an object', function() { try { util.delProp(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'obj must be an object!'); } }); - it('delProp() - key is required', function(){ + it('delProp() - key is required', function() { try { util.delProp({}); - } catch (err){ + } catch (err) { err.should.have.property('message', 'key is required!'); } }); - it('setGetter()', function(){ + it('setGetter()', function() { var obj = { a: { b: 1 @@ -128,146 +130,150 @@ describe('util', function(){ } }; - util.setGetter(obj, 'a.b', function(){ + util.setGetter(obj, 'a.b', function() { return 100; }); + obj.a.b.should.eql(100); - util.setGetter(obj, 'c', function(){ + util.setGetter(obj, 'c', function() { return 200; }); + obj.c.should.eql(200); - util.setGetter(obj, 'd.e.f', function(){ + util.setGetter(obj, 'd.e.f', function() { return 'haha'; }); + obj.d.e.f.should.eql('haha'); - util.setGetter(obj, 'a.c.h', function(){ + util.setGetter(obj, 'a.c.h', function() { return 'ach'; }); + obj.a.c.h.should.eql('ach'); }); - it('setGetter() - obj must be an object', function(){ + it('setGetter() - obj must be an object', function() { try { util.setGetter(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'obj must be an object!'); } }); - it('setGetter() - key is required', function(){ + it('setGetter() - key is required', function() { try { util.setGetter({}); - } catch (err){ + } catch (err) { err.should.have.property('message', 'key is required!'); } }); - it('setGetter() - fn must be a function', function(){ + it('setGetter() - fn must be a function', function() { try { util.setGetter({}, 'test'); - } catch (err){ + } catch (err) { err.should.have.property('message', 'fn must be a function!'); } }); - it('arr2obj()', function(){ + it('arr2obj()', function() { util.arr2obj(['a', 'b'], 1).should.eql({a: 1, b: 1}); }); - it('arr2obj() - arr must be an array', function(){ + it('arr2obj() - arr must be an array', function() { try { util.arr2obj(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'arr must be an array!'); } }); - it('arrayEqual()', function(){ + it('arrayEqual()', function() { util.arrayEqual(['a', 'b'], ['a', 'b']).should.be.true; util.arrayEqual(['1', 2], ['1', '2']).should.be.false; }); - it('arrayEqual() - a must be an array', function(){ + it('arrayEqual() - a must be an array', function() { try { util.arrayEqual(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'a must be an array!'); } }); - it('arrayEqual() - b must be an array', function(){ + it('arrayEqual() - b must be an array', function() { try { util.arrayEqual([]); - } catch (err){ + } catch (err) { err.should.have.property('message', 'b must be an array!'); } }); - it('cloneArray()', function(){ + it('cloneArray()', function() { util.cloneArray([1, 2, 3]).should.eql([1, 2, 3]); util.cloneArray([1, [2, 3], [4, [5, 6]]]).should.eql([1, [2, 3], [4, [5, 6]]]); }); - it('cloneArray() - arr must be an array', function(){ + it('cloneArray() - arr must be an array', function() { try { util.cloneArray(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'arr must be an array!'); } }); - it('contains()', function(){ + it('contains()', function() { util.contains(['1', '2', 3], '1').should.be.true; util.contains(['1', '2', 3], '3').should.be.false; }); - it('contains() - arr must be an array', function(){ + it('contains() - arr must be an array', function() { try { util.contains(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'arr must be an array!'); } }); - it('reverse()', function(){ + it('reverse()', function() { var arr = [1, '2', 'w']; util.reverse(arr).should.eql(['w', '2', 1]); }); - it('reverse() - arr must be an array', function(){ + it('reverse() - arr must be an array', function() { try { util.reverse(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'arr must be an array!'); } }); - it('shuffle()', function(){ + it('shuffle()', function() { var arr = util.shuffle([1, 2, 3]); arr.sort().should.eql([1, 2, 3]); }); - it('parseArgs() - arr must be an array', function(){ + it('parseArgs() - arr must be an array', function() { try { util.parseArgs(); - } catch (err){ + } catch (err) { err.should.have.property('message', 'arr must be an array!'); } }); - it('parseArgs()', function(){ + it('parseArgs()', function() { util.parseArgs('name').should.eql({name: 1}); util.parseArgs('name', -1).should.eql({name: -1}); util.parseArgs('name -date').should.eql({name: 1, date: -1}); util.parseArgs('name -date +priority').should.eql({name: 1, date: -1, priority: 1}); }); - it('extend()', function(){ + it('extend()', function() { util.extend({a: 1}, {b: 2}).should.eql({a: 1, b: 2}); util.extend({a: 1}, undefined, {b: 2}).should.eql({a: 1, b: 2}); }); -}); \ No newline at end of file +});