From 3250cd2e4ce83971bbb92aa62b7fe0242b3ca7eb Mon Sep 17 00:00:00 2001 From: Victor Parpoil Date: Mon, 13 Jan 2025 17:57:10 +0100 Subject: [PATCH 1/6] feat: autovalue can be async - clean must be awaited --- README.md | 10 ++++++---- lib/SimpleSchema.js | 8 ++++---- lib/clean.js | 4 ++-- lib/clean/AutoValueRunner.js | 4 ++-- lib/clean/setAutoValues.js | 11 +++++++---- 5 files changed, 21 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 4843cd2..1c32538 100644 --- a/README.md +++ b/README.md @@ -319,7 +319,7 @@ import SimpleSchema from "meteor/aldeed:simple-schema"; const mySchema = new SimpleSchema({ name: String }); const doc = { name: 123 }; -const cleanDoc = mySchema.clean(doc); +const cleanDoc = await mySchema.clean(doc); // cleanDoc is now mutated to hopefully have a better chance of passing validation console.log(typeof cleanDoc.name); // string ``` @@ -331,7 +331,7 @@ import SimpleSchema from "meteor/aldeed:simple-schema"; const mySchema = new SimpleSchema({ name: String }); const modifier = { $set: { name: 123 } }; -const cleanModifier = mySchema.clean(modifier); +const cleanModifier = await mySchema.clean(modifier); // doc is now mutated to hopefully have a better chance of passing validation console.log(typeof cleanModifier.$set.name); // string ``` @@ -835,7 +835,7 @@ Prior to SimpleSchema 2.0, objects that are instances of a custom class were con _Used by the cleaning process but not by validation_ -When you call `simpleSchemaInstance.clean()` with `trimStrings` set to `true`, all string values are trimmed of leading and trailing whitespace. If you set `trim` to `false` for certain keys in their schema definition, those keys will be skipped. +When you call `await simpleSchemaInstance.clean()` with `trimStrings` set to `true`, all string values are trimmed of leading and trailing whitespace. If you set `trim` to `false` for certain keys in their schema definition, those keys will be skipped. ### custom @@ -845,7 +845,7 @@ Refer to the [Custom Validation](#custom-field-validation) section. _Used by the cleaning process but not by validation_ -Set this to any value that you want to be used as the default when an object does not include this field or has this field set to `undefined`. This value will be injected into the object by a call to `mySimpleSchema.clean()` with `getAutovalues: true`. +Set this to any value that you want to be used as the default when an object does not include this field or has this field set to `undefined`. This value will be injected into the object by a call to `await mySimpleSchema.clean()` with `getAutovalues: true`. Note the following points of confusion: @@ -862,6 +862,8 @@ _Used by the cleaning process but not by validation_ The `autoValue` option allows you to specify a function that is called by `simpleSchemaInstance.clean()` to potentially change the value of a property in the object being cleaned. This is a powerful feature that allows you to set up either forced values or default values, potentially based on the values of other fields in the object. +The `autoValue` function can be an `async` function + An `autoValue` function `this` context provides a variety of properties and methods to help you determine what you should return: - `this.closestSubschemaFieldName`: If your schema is used as a subschema in another schema, this will be set to the name of the key that references the schema. Otherwise it will be `null`. diff --git a/lib/SimpleSchema.js b/lib/SimpleSchema.js index 172f20d..3c6466e 100644 --- a/lib/SimpleSchema.js +++ b/lib/SimpleSchema.js @@ -717,12 +717,12 @@ class SimpleSchema { } validator(options = {}) { - return (obj) => { + return async(obj) => { const optionsClone = { ...options }; if (options.clean === true) { // Do this here and pass into both functions for better performance optionsClone.mongoObject = new MongoObject(obj, this.blackboxKeys()); - this.clean(obj, optionsClone); + await this.clean(obj, optionsClone); } if (options.returnErrorsPromise) { return this.validateAndReturnErrorsPromise(obj, optionsClone); @@ -735,8 +735,8 @@ class SimpleSchema { return this.validator({ ...options, returnErrorsPromise: true }); } - clean(...args) { - return clean(this, ...args); + async clean(...args) { + return await clean(this, ...args); } /** diff --git a/lib/clean.js b/lib/clean.js index d9d6de1..4266d68 100644 --- a/lib/clean.js +++ b/lib/clean.js @@ -30,7 +30,7 @@ const operatorsToIgnoreValue = ['$unset', '$currentDate']; * type convert where possible, and inject automatic/default values. Use the options * to skip one or more of these. */ -function clean(ss, doc, options = {}) { +async function clean(ss, doc, options = {}) { // By default, doc will be filtered and autoconverted options = { isModifier: looksLikeModifier(doc), @@ -171,7 +171,7 @@ function clean(ss, doc, options = {}) { // Set automatic values options.getAutoValues - && setAutoValues( + && await setAutoValues( ss.autoValueFunctions(), mongoObject, options.isModifier, diff --git a/lib/clean/AutoValueRunner.js b/lib/clean/AutoValueRunner.js index 23a8e4a..781cbf7 100644 --- a/lib/clean/AutoValueRunner.js +++ b/lib/clean/AutoValueRunner.js @@ -16,7 +16,7 @@ export default class AutoValueRunner { this.doneKeys = []; } - runForPosition({ + async runForPosition({ key: affectedKey, operator, position, @@ -46,7 +46,7 @@ export default class AutoValueRunner { } } - const autoValue = func.call({ + const autoValue = await func.call({ closestSubschemaFieldName: closestSubschemaFieldName.length ? closestSubschemaFieldName : null, field(fName) { return getFieldInfo(mongoObject, closestSubschemaFieldName + fName); diff --git a/lib/clean/setAutoValues.js b/lib/clean/setAutoValues.js index 31a4420..8129422 100755 --- a/lib/clean/setAutoValues.js +++ b/lib/clean/setAutoValues.js @@ -36,10 +36,11 @@ export function sortAutoValueFunctions(autoValueFunctions) { * Updates doc with automatic values from autoValue functions or default * values from defaultValue. Modifies the referenced object in place. */ -function setAutoValues(autoValueFunctions, mongoObject, isModifier, isUpsert, extendedAutoValueContext) { +async function setAutoValues(autoValueFunctions, mongoObject, isModifier, isUpsert, extendedAutoValueContext) { const sortedAutoValueFunctions = sortAutoValueFunctions(autoValueFunctions); - sortedAutoValueFunctions.forEach(({ func, fieldName, closestSubschemaFieldName }) => { + for (const sortedItem of sortedAutoValueFunctions) { + const { func, fieldName, closestSubschemaFieldName } = sortedItem; const avRunner = new AutoValueRunner({ closestSubschemaFieldName, extendedAutoValueContext, @@ -53,8 +54,10 @@ function setAutoValues(autoValueFunctions, mongoObject, isModifier, isUpsert, ex // Run the autoValue function once for each place in the object that // has a value or that potentially should. - positions.forEach(avRunner.runForPosition.bind(avRunner)); - }); + for (const position of positions) { + await avRunner.runForPosition(position); + } + } } export default setAutoValues; From 28635a422705644cb229887952d85418b46c4a03 Mon Sep 17 00:00:00 2001 From: Victor Parpoil Date: Mon, 13 Jan 2025 18:11:00 +0100 Subject: [PATCH 2/6] feat: update tests for async clean --- lib/SimpleSchema.tests.js | 16 +- lib/SimpleSchema_autoValueFunctions.tests.js | 15 +- lib/clean.tests.js | 202 +++++---------- lib/clean/autoValue.tests.js | 201 ++++++++------- lib/clean/defaultValue.tests.js | 258 +++++++++++-------- 5 files changed, 343 insertions(+), 349 deletions(-) diff --git a/lib/SimpleSchema.tests.js b/lib/SimpleSchema.tests.js index 2f472e3..ec3cbe0 100644 --- a/lib/SimpleSchema.tests.js +++ b/lib/SimpleSchema.tests.js @@ -226,7 +226,7 @@ describe('SimpleSchema', function () { }); }); - it('Safely sets defaultValues on subschemas nested in arrays', function () { + it('Safely sets defaultValues on subschemas nested in arrays', async function () { const nestedSchema = new SimpleSchema({ nested: { type: Array, @@ -247,14 +247,14 @@ describe('SimpleSchema', function () { }); const context = nestedSchema.newContext(); - const cleaned = context.clean({ - $set: { - nested: [ - { somethingOptional: 'q' }, - { somethingOptional: 'z' }, - ], + const cleaned = await context.clean( + { + $set: { + nested: [{ somethingOptional: 'q' }, { somethingOptional: 'z' }], + }, }, - }, { modifier: true }); + { modifier: true }, + ); expect(cleaned).to.deep.equal({ $set: { diff --git a/lib/SimpleSchema_autoValueFunctions.tests.js b/lib/SimpleSchema_autoValueFunctions.tests.js index fcade89..6c1096f 100644 --- a/lib/SimpleSchema_autoValueFunctions.tests.js +++ b/lib/SimpleSchema_autoValueFunctions.tests.js @@ -153,5 +153,18 @@ describe('SimpleSchema - autoValueFunctions', function () { expect(autoValueFunctions[1].closestSubschemaFieldName).to.equal('a.b.$'); }); - it('async functions'); + it('async functions', async function () { + const schema = new SimpleSchema({ + a: { + type: String, + autoValue() { + return new Promise((resolve) => { + resolve('a'); + }); + }, + }, + }); + const b = await schema.clean({}); + expect(b).to.deep.equal({ a: 'a' }); + }); }); diff --git a/lib/clean.tests.js b/lib/clean.tests.js index 7f0f173..272a084 100644 --- a/lib/clean.tests.js +++ b/lib/clean.tests.js @@ -188,8 +188,8 @@ const ss = new SimpleSchema({ }); function getTest(given, expected, isModifier) { - return function () { - ss.clean(given, { isModifier, mutate: true }); + return async function () { + await ss.clean(given, { isModifier, mutate: true }); expect(given).to.deep.equal(expected); }; } @@ -692,9 +692,9 @@ describe('clean', function () { ); }); - it('trim strings', function () { - function doTest(isModifier, given, expected) { - const cleanObj = ss.clean(given, { + it('trim strings', async function () { + async function doTest(isModifier, given, expected) { + const cleanObj = await ss.clean(given, { mutate: true, filter: false, autoConvert: false, @@ -707,42 +707,26 @@ describe('clean', function () { } // DOC - doTest( - false, - { string: ' This is a string ' }, - { string: 'This is a string' }, - ); + await doTest(false, { string: ' This is a string ' }, { string: 'This is a string' }); // $SET - doTest( - true, - { $set: { string: ' This is a string ' } }, - { $set: { string: 'This is a string' } }, - ); + await doTest(true, { $set: { string: ' This is a string ' } }, { $set: { string: 'This is a string' } }); // $UNSET is ignored - doTest( - true, - { $unset: { string: ' This is a string ' } }, - { $unset: { string: ' This is a string ' } }, - ); + await doTest(true, { $unset: { string: ' This is a string ' } }, { $unset: { string: ' This is a string ' } }); // $SETONINSERT - doTest( - true, - { $setOnInsert: { string: ' This is a string ' } }, - { $setOnInsert: { string: 'This is a string' } }, - ); + await doTest(true, { $setOnInsert: { string: ' This is a string ' } }, { $setOnInsert: { string: 'This is a string' } }); // $ADDTOSET - doTest( + await doTest( true, { $addToSet: { minMaxStringArray: ' This is a string ' } }, { $addToSet: { minMaxStringArray: 'This is a string' } }, ); // $ADDTOSET WITH EACH - doTest( + await doTest( true, { $addToSet: { @@ -753,49 +737,33 @@ describe('clean', function () { ); // $PUSH - doTest( - true, - { $push: { minMaxStringArray: ' This is a string ' } }, - { $push: { minMaxStringArray: 'This is a string' } }, - ); + await doTest(true, { $push: { minMaxStringArray: ' This is a string ' } }, { $push: { minMaxStringArray: 'This is a string' } }); // $PUSH WITH EACH - doTest( + await doTest( true, { $push: { minMaxStringArray: { $each: [' This is a string '] } } }, { $push: { minMaxStringArray: { $each: ['This is a string'] } } }, ); // $PULL - doTest( - true, - { $pull: { minMaxStringArray: ' This is a string ' } }, - { $pull: { minMaxStringArray: 'This is a string' } }, - ); + await doTest(true, { $pull: { minMaxStringArray: ' This is a string ' } }, { $pull: { minMaxStringArray: 'This is a string' } }); // $POP - doTest( - true, - { $pop: { minMaxStringArray: ' This is a string ' } }, - { $pop: { minMaxStringArray: 'This is a string' } }, - ); + await doTest(true, { $pop: { minMaxStringArray: ' This is a string ' } }, { $pop: { minMaxStringArray: 'This is a string' } }); // $PULLALL - doTest( + await doTest( true, { $pullAll: { minMaxStringArray: [' This is a string '] } }, { $pullAll: { minMaxStringArray: ['This is a string'] } }, ); // Trim false - doTest( - false, - { noTrimString: ' This is a string ' }, - { noTrimString: ' This is a string ' }, - ); + await doTest(false, { noTrimString: ' This is a string ' }, { noTrimString: ' This is a string ' }); // Trim false with autoConvert - const cleanObj = ss.clean( + const cleanObj = await ss.clean( { noTrimString: ' This is a string ' }, { filter: false, @@ -810,7 +778,7 @@ describe('clean', function () { }); describe('miscellaneous', function () { - it('does not $unset when the prop is within an object that is already being $set', function () { + it('does not $unset when the prop is within an object that is already being $set', async function () { const optionalInObject = new SimpleSchema({ requiredObj: { type: Object, @@ -827,24 +795,24 @@ describe('clean', function () { const myObj = { $set: { requiredObj: { requiredProp: 'blah', optionalProp: '' } }, }; - optionalInObject.clean(myObj, { isModifier: true, mutate: true }); + await optionalInObject.clean(myObj, { isModifier: true, mutate: true }); expect(myObj).to.deep.equal({ $set: { requiredObj: { requiredProp: 'blah' } }, }); }); - it('type convert to array', function () { + it('type convert to array', async function () { const myObj1 = { allowedStringsArray: 'tuna' }; - ss.clean(myObj1, { mutate: true }); + await ss.clean(myObj1, { mutate: true }); expect(myObj1).to.deep.equal({ allowedStringsArray: ['tuna'] }); const myObj2 = { $set: { allowedStringsArray: 'tuna' } }; - ss.clean(myObj2, { isModifier: true, mutate: true }); + await ss.clean(myObj2, { isModifier: true, mutate: true }); expect(myObj2).to.deep.equal({ $set: { allowedStringsArray: ['tuna'] } }); }); - it('multi-dimensional arrays', function () { + it('multi-dimensional arrays', async function () { const schema = new SimpleSchema({ geometry: { type: Object, @@ -871,16 +839,16 @@ describe('clean', function () { }; const expected = JSON.stringify(doc); - expect(JSON.stringify(schema.clean(doc))).to.deep.equal(expected); + expect(JSON.stringify(await schema.clean(doc))).to.deep.equal(expected); }); - it('removeNullsFromArrays removes nulls from arrays', function () { + it('removeNullsFromArrays removes nulls from arrays', async function () { const schema = new SimpleSchema({ names: Array, 'names.$': String, }); - const cleanedObject = schema.clean( + const cleanedObject = await schema.clean( { names: [null, 'foo', null], }, @@ -892,14 +860,14 @@ describe('clean', function () { }); }); - it('removeNullsFromArrays does not remove non-null objects from arrays', function () { + it('removeNullsFromArrays does not remove non-null objects from arrays', async function () { const schema = new SimpleSchema({ a: Array, 'a.$': Object, 'a.$.b': Number, }); - const cleanedObject = schema.clean( + const cleanedObject = await schema.clean( { $set: { a: [{ b: 1 }], @@ -916,7 +884,7 @@ describe('clean', function () { }); }); - it('remove object', function () { + it('remove object', async function () { const schema = new SimpleSchema({ names: { type: Array }, 'names.$': { type: String }, @@ -925,14 +893,14 @@ describe('clean', function () { const doc = { names: [{ hello: 'world' }], }; - schema.clean(doc, { mutate: true }); + await schema.clean(doc, { mutate: true }); expect(doc).to.deep.equal({ names: [], }); }); }); - it('should clean sub schemas', function () { + it('should clean sub schemas', async function () { const doubleNestedSchema = new SimpleSchema({ integer: SimpleSchema.Integer, }); @@ -946,7 +914,7 @@ describe('clean', function () { 'nested.$': nestedSchema, }); - const cleanedObject = schema.clean({ + const cleanedObject = await schema.clean({ nested: [ { doubleNested: { @@ -967,7 +935,7 @@ describe('clean', function () { }); }); - describe('with SimpleSchema.oneOf(String, Number, Date)', function () { + describe('with SimpleSchema.oneOf(String, Number, Date)', async function () { const oneOfSchema = new SimpleSchema({ field: { type: SimpleSchema.oneOf(String, Number, Date), @@ -978,21 +946,21 @@ describe('clean', function () { 'nested.field': SimpleSchema.oneOf(String, Number, Date), }); - function doTest(given, expected) { - const cleanObj = oneOfSchema.clean(given, { mutate: true }); + async function doTest(given, expected) { + const cleanObj = await oneOfSchema.clean(given, { mutate: true }); expect(cleanObj).to.deep.equal(expected); } - it('should not convert a string', function () { - doTest({ field: 'I am a string' }, { field: 'I am a string' }); + it('should not convert a string', async function () { + await doTest({ field: 'I am a string' }, { field: 'I am a string' }); }); - it('should not convert a number', function () { - doTest({ field: 12345 }, { field: 12345 }); + it('should not convert a number', async function () { + await doTest({ field: 12345 }, { field: 12345 }); }); - it('should not convert a Date', function () { - doTest({ field: new Date(12345) }, { field: new Date(12345) }); + it('should not convert a Date', async function () { + await doTest({ field: new Date(12345) }, { field: new Date(12345) }); }); - it('should convert a Date if no Date in oneOf', function () { + it('should convert a Date if no Date in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { type: SimpleSchema.oneOf(String, Number), @@ -1001,85 +969,64 @@ describe('clean', function () { const date = new Date(12345); const dateStrng = date.toString(); - const cleanObj = schemaNoDate.clean({ field: date }, { mutate: true }); + const cleanObj = await schemaNoDate.clean({ field: date }, { mutate: true }); expect(cleanObj).to.deep.equal({ field: dateStrng }); }); - it('should convert a String if no String in oneOf', function () { + it('should convert a String if no String in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { type: SimpleSchema.oneOf(Number, Date), }, }); - const cleanObj = schemaNoDate.clean({ field: '12345' }, { mutate: true }); + const cleanObj = await schemaNoDate.clean({ field: '12345' }, { mutate: true }); expect(cleanObj).to.deep.equal({ field: 12345 }); }); - it('should convert a Number if no Number in oneOf', function () { + it('should convert a Number if no Number in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { type: SimpleSchema.oneOf(String, Date), }, }); - const cleanObj = schemaNoDate.clean({ field: 12345 }, { mutate: true }); + const cleanObj = await schemaNoDate.clean({ field: 12345 }, { mutate: true }); expect(cleanObj).to.deep.equal({ field: '12345' }); }); describe('with modifiers', function () { - it('should not convert a string', function () { - doTest( - { $set: { field: 'I am a string' } }, - { $set: { field: 'I am a string' } }, - ); + it('should not convert a string', async function () { + await doTest({ $set: { field: 'I am a string' } }, { $set: { field: 'I am a string' } }); }); - it('should not convert a nested string', function () { - doTest( - { $set: { field: 'I am a string' } }, - { $set: { field: 'I am a string' } }, - ); + it('should not convert a nested string', async function () { + await doTest({ $set: { field: 'I am a string' } }, { $set: { field: 'I am a string' } }); }); - it('should not convert a number', function () { - doTest({ $set: { field: 12345 } }, { $set: { field: 12345 } }); + it('should not convert a number', async function () { + await doTest({ $set: { field: 12345 } }, { $set: { field: 12345 } }); }); - it('should not convert a Date', function () { - doTest( - { $set: { field: new Date(12345) } }, - { $set: { field: new Date(12345) } }, - ); + it('should not convert a Date', async function () { + await doTest({ $set: { field: new Date(12345) } }, { $set: { field: new Date(12345) } }); }); describe('nested operator', function () { - it('should not convert a string', function () { - doTest( - { $set: { 'nested.field': 'I am a string' } }, - { $set: { 'nested.field': 'I am a string' } }, - ); + it('should not convert a string', async function () { + await doTest({ $set: { 'nested.field': 'I am a string' } }, { $set: { 'nested.field': 'I am a string' } }); }); - it('should not convert a nested string', function () { - doTest( - { $set: { 'nested.field': 'I am a string' } }, - { $set: { 'nested.field': 'I am a string' } }, - ); + it('should not convert a nested string', async function () { + await doTest({ $set: { 'nested.field': 'I am a string' } }, { $set: { 'nested.field': 'I am a string' } }); }); - it('should not convert a number', function () { - doTest( - { $set: { 'nested.field': 12345 } }, - { $set: { 'nested.field': 12345 } }, - ); + it('should not convert a number', async function () { + await doTest({ $set: { 'nested.field': 12345 } }, { $set: { 'nested.field': 12345 } }); }); - it('should not convert a Date', function () { - doTest( - { $set: { 'nested.field': new Date(12345) } }, - { $set: { 'nested.field': new Date(12345) } }, - ); + it('should not convert a Date', async function () { + await doTest({ $set: { 'nested.field': new Date(12345) } }, { $set: { 'nested.field': new Date(12345) } }); }); }); - it('should convert a Date if no Date in oneOf', function () { + it('should convert a Date if no Date in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { type: SimpleSchema.oneOf(String, Number), @@ -1088,38 +1035,29 @@ describe('clean', function () { const date = new Date(12345); const dateString = date.toString(); - const cleanObj = schemaNoDate.clean( - { $set: { field: date } }, - { mutate: true }, - ); + const cleanObj = await schemaNoDate.clean({ $set: { field: date } }, { mutate: true }); expect(cleanObj).to.deep.equal({ $set: { field: dateString } }); }); - it('should convert a String if no String in oneOf', function () { + it('should convert a String if no String in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { type: SimpleSchema.oneOf(Number, Date), }, }); - const cleanObj = schemaNoDate.clean( - { $set: { field: '12345' } }, - { mutate: true }, - ); + const cleanObj = await schemaNoDate.clean({ $set: { field: '12345' } }, { mutate: true }); expect(cleanObj).to.deep.equal({ $set: { field: 12345 } }); }); - it('should convert a Number if no Number in oneOf', function () { + it('should convert a Number if no Number in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { type: SimpleSchema.oneOf(String, Date), }, }); - const cleanObj = schemaNoDate.clean( - { $set: { field: 12345 } }, - { mutate: true }, - ); + const cleanObj = await schemaNoDate.clean({ $set: { field: 12345 } }, { mutate: true }); expect(cleanObj).to.deep.equal({ $set: { field: '12345' } }); }); }); diff --git a/lib/clean/autoValue.tests.js b/lib/clean/autoValue.tests.js index b52dbf8..272e5c7 100644 --- a/lib/clean/autoValue.tests.js +++ b/lib/clean/autoValue.tests.js @@ -5,7 +5,7 @@ import { SimpleSchema } from '../SimpleSchema'; describe('autoValue', function () { describe('has correct information in function context', function () { - it('empty', function () { + it('empty', async function () { const schema = new SimpleSchema({ foo: { type: String, @@ -44,10 +44,10 @@ describe('autoValue', function () { }, }, }); - schema.clean({}); + await schema.clean({}); }); - it('normal other key', function () { + it('normal other key', async function () { const schema = new SimpleSchema({ foo: { type: String, @@ -84,12 +84,12 @@ describe('autoValue', function () { }, }, }); - schema.clean({ + await schema.clean({ foo: 'clown', }); }); - it('normal self and other key', function () { + it('normal self and other key', async function () { const schema = new SimpleSchema({ foo: { type: String, @@ -126,13 +126,13 @@ describe('autoValue', function () { }, }, }); - schema.clean({ + await schema.clean({ foo: 'clown', bar: true, }); }); - it('parentField', function () { + it('parentField', async function () { const schema = new SimpleSchema({ foo: { type: Object, @@ -150,12 +150,12 @@ describe('autoValue', function () { }, }, }); - schema.clean({ + await schema.clean({ foo: {}, }); }); - it('closestSubschemaFieldName set', function () { + it('closestSubschemaFieldName set', async function () { const schema1 = new SimpleSchema({ dug: { type: Boolean, @@ -172,12 +172,12 @@ describe('autoValue', function () { optional: true, }, }); - schema2.clean({ + await schema2.clean({ dig: {}, }); }); - it('normal self and no other key with unset', function () { + it('normal self and no other key with unset', async function () { const schema = new SimpleSchema({ foo: { type: String, @@ -219,10 +219,10 @@ describe('autoValue', function () { const doc = { bar: false, }; - expect(schema.clean(doc)).to.deep.equal({}); + expect(await schema.clean(doc)).to.deep.equal({}); }); - it('$set self and no other key', function () { + it('$set self and no other key', async function () { const schema = new SimpleSchema({ foo: { type: String, @@ -265,7 +265,7 @@ describe('autoValue', function () { bar: false, }, }; - schema.clean(doc); + await schema.clean(doc); expect(doc).to.deep.equal({ $set: { bar: false, @@ -273,7 +273,7 @@ describe('autoValue', function () { }); }); - it('$set self and another key and change self', function () { + it('$set self and another key and change self', async function () { const schema = new SimpleSchema({ foo: { type: String, @@ -319,7 +319,7 @@ describe('autoValue', function () { bar: false, }, }; - expect(schema.clean(doc)).to.deep.equal({ + expect(await schema.clean(doc)).to.deep.equal({ $set: { foo: 'clown', bar: true, @@ -327,7 +327,7 @@ describe('autoValue', function () { }); }); - it('adds $set when missing', function () { + it('adds $set when missing', async function () { const schema = new SimpleSchema({ foo: { type: String, @@ -369,7 +369,7 @@ describe('autoValue', function () { }, }); - expect(schema.clean({}, { isModifier: true })).to.deep.equal({ + expect(await schema.clean({}, { isModifier: true })).to.deep.equal({ $set: { bar: true, }, @@ -377,7 +377,7 @@ describe('autoValue', function () { }); }); - it('content autoValues', function () { + it('content autoValues', async function () { const schema = new SimpleSchema({ content: { type: String, @@ -414,7 +414,7 @@ describe('autoValue', function () { }); // Normal object - let result = schema.clean({ content: 'foo' }); + let result = await schema.clean({ content: 'foo' }); expect(result).to.deep.equal({ content: 'foo', updatesHistory: [ @@ -426,7 +426,7 @@ describe('autoValue', function () { }); // $set - result = schema.clean({ $set: { content: 'foo' } }); + result = await schema.clean({ $set: { content: 'foo' } }); expect(result).to.deep.equal({ $set: { content: 'foo', @@ -442,7 +442,7 @@ describe('autoValue', function () { it('async content'); - it('array of objects autoValues', function () { + it('array of objects autoValues', async function () { const schema = new SimpleSchema({ avArrayOfObjects: { type: Array, @@ -462,7 +462,7 @@ describe('autoValue', function () { }, }); - let result = schema.clean({ + let result = await schema.clean({ $push: { avArrayOfObjects: { a: 'b', @@ -479,7 +479,7 @@ describe('autoValue', function () { }, }); - result = schema.clean({ + result = await schema.clean({ $set: { avArrayOfObjects: [{ a: 'b', @@ -504,7 +504,7 @@ describe('autoValue', function () { it('async array of objects autoValues'); - it('$each in autoValue pseudo modifier', function () { + it('$each in autoValue pseudo modifier', async function () { const schema = new SimpleSchema({ psuedoEach: { type: Array, @@ -524,7 +524,7 @@ describe('autoValue', function () { }, }); - const result = schema.clean({ + const result = await schema.clean({ $set: { psuedoEach: ['foo', 'bar'], }, @@ -541,7 +541,7 @@ describe('autoValue', function () { it('async $each in autoValue pseudo modifier'); - it('simple autoValues', function () { + it('simple autoValues', async function () { const schema = new SimpleSchema({ name: { type: String, @@ -570,7 +570,7 @@ describe('autoValue', function () { }, }); - let result = schema.clean({ + let result = await schema.clean({ name: 'Test', firstWord: 'Illegal to manually set value', }); @@ -581,7 +581,7 @@ describe('autoValue', function () { updateCount: 0, }); - result = schema.clean({ + result = await schema.clean({ name: 'Test', someDefault: 20, }); @@ -592,7 +592,7 @@ describe('autoValue', function () { updateCount: 0, }); - result = schema.clean({ + result = await schema.clean({ $set: { name: 'Test', someDefault: 20, @@ -610,7 +610,7 @@ describe('autoValue', function () { it('async simple autoValues'); - it('objects in arrays', function () { + it('objects in arrays', async function () { const subSchema = new SimpleSchema({ value: { type: String, @@ -632,16 +632,19 @@ describe('autoValue', function () { }, }); - const result = schema.clean({ - $set: { - 'children.$.value': 'should be overridden by autovalue', + const result = await schema.clean( + { + $set: { + 'children.$.value': 'should be overridden by autovalue', + }, }, - }, { isModifier: true }); + { isModifier: true }, + ); expect(result.$set['children.$.value']).to.equal('autovalue'); }); - it('operator correct for $pull', function () { + it('operator correct for $pull', async function () { let called = false; const schema = new SimpleSchema({ @@ -657,7 +660,7 @@ describe('autoValue', function () { }, }); - schema.clean({ + await schema.clean({ $pull: { foo: 'bar', }, @@ -666,7 +669,7 @@ describe('autoValue', function () { expect(called).to.equal(true); }); - it('issue 340', function () { + it('issue 340', async function () { let called = 0; const schema = new SimpleSchema({ @@ -684,10 +687,10 @@ describe('autoValue', function () { }, }); - schema.clean({ + await schema.clean({ field1: 1, }); - schema.clean({ + await schema.clean({ $set: { field1: 1, }, @@ -696,56 +699,62 @@ describe('autoValue', function () { expect(called).to.equal(2); }); - it('should allow getting previous autoValue in later autoValue', function () { - const schema = new SimpleSchema({ - amount: Number, - tax: { - type: Number, - optional: true, - autoValue() { - return 0.5; + it('should allow getting previous autoValue in later autoValue', async function () { + const schema = new SimpleSchema( + { + amount: Number, + tax: { + type: Number, + optional: true, + autoValue() { + return 0.5; + }, }, - }, - total: { - type: Number, - optional: true, - autoValue() { - const amount = this.field('amount').value || 0; - const tax = this.field('tax').value || 0; - return amount * (1 + tax); + total: { + type: Number, + optional: true, + autoValue() { + const amount = this.field('amount').value || 0; + const tax = this.field('tax').value || 0; + return amount * (1 + tax); + }, }, }, - }, { - clean: { - filter: false, - autoConvert: false, + { + clean: { + filter: false, + autoConvert: false, + }, }, - }); + ); - expect(schema.clean({ amount: 1 })).to.deep.equal({ + expect(await schema.clean({ amount: 1 })).to.deep.equal({ amount: 1, tax: 0.5, total: 1.5, }); }); - it('clean options should be merged when extending', function () { - const schema1 = new SimpleSchema({ - a: String, - }, { - clean: { - filter: false, - autoConvert: false, + it('clean options should be merged when extending', async function () { + const schema1 = new SimpleSchema( + { + a: String, }, - }); + { + clean: { + filter: false, + autoConvert: false, + }, + }, + ); const schema2 = new SimpleSchema({}); schema2.extend(schema1); - expect(schema2.clean({ a: 1 })).to.deep.equal({ a: 1 }); + expect(await schema2.clean({ a: 1 })).to.deep.equal({ a: 1 }); }); - it('array items', function () { + it('array items', async function () { const schema = new SimpleSchema({ tags: { type: Array, @@ -762,19 +771,19 @@ describe('autoValue', function () { const obj = { tags: [], }; - expect(schema.clean(obj)).to.deep.equal({ + expect(await schema.clean(obj)).to.deep.equal({ tags: [], }); const obj2 = { tags: ['FOO', 'BAR'], }; - expect(schema.clean(obj2)).to.deep.equal({ + expect(await schema.clean(obj2)).to.deep.equal({ tags: ['foo', 'bar'], }); }); - it('updates existing objects when deeply nested (plain)', function () { + it('updates existing objects when deeply nested (plain)', async function () { const schema = new SimpleSchema({ nested: Array, 'nested.$': Object, @@ -789,7 +798,7 @@ describe('autoValue', function () { }, }); - const cleanedObject = schema.clean({ + const cleanedObject = await schema.clean({ nested: [ { doubleNested: {}, @@ -818,7 +827,7 @@ describe('autoValue', function () { }); }); - it('updates existing objects when deeply nested (modifier)', function () { + it('updates existing objects when deeply nested (modifier)', async function () { const schema = new SimpleSchema({ nested: Array, 'nested.$': Object, @@ -833,7 +842,7 @@ describe('autoValue', function () { }, }); - const cleanedObject = schema.clean({ + const cleanedObject = await schema.clean({ $push: { nested: { doubleNested: {}, @@ -852,7 +861,7 @@ describe('autoValue', function () { }); }); - it('updates deeply nested with empty $set', function () { + it('updates deeply nested with empty $set', async function () { const schema = new SimpleSchema({ nested: Array, 'nested.$': Object, @@ -874,7 +883,7 @@ describe('autoValue', function () { }, }); - const cleanedObject = schema.clean({ + const cleanedObject = await schema.clean({ $set: { nested: [{}], }, @@ -882,16 +891,18 @@ describe('autoValue', function () { expect(cleanedObject).to.deep.equal({ $set: { - nested: [{ - doubleNested: { - integer: 5, + nested: [ + { + doubleNested: { + integer: 5, + }, }, - }], + ], }, }); }); - it('updates deeply nested with $set having dotted array key', function () { + it('updates deeply nested with $set having dotted array key', async function () { const schema = new SimpleSchema({ nested: Array, 'nested.$': Object, @@ -906,7 +917,7 @@ describe('autoValue', function () { }, }); - const cleanedObject = schema.clean({ + const cleanedObject = await schema.clean({ $set: { 'nested.0.doubleNested': {}, }, @@ -921,7 +932,7 @@ describe('autoValue', function () { }); }); - it('should add auto values to sub schemas for plain objects', function () { + it('should add auto values to sub schemas for plain objects', async function () { const doubleNestedSchema = new SimpleSchema({ integer: { type: SimpleSchema.Integer, @@ -942,7 +953,7 @@ describe('autoValue', function () { 'nested.$': nestedSchema, }); - const cleanedObject = schema.clean({ + const cleanedObject = await schema.clean({ nested: [ { doubleNested: {}, @@ -971,7 +982,7 @@ describe('autoValue', function () { }); }); - it('should add auto values to sub schemas for modifiers objects', function () { + it('should add auto values to sub schemas for modifiers objects', async function () { const doubleNestedSchema = new SimpleSchema({ integer: { type: SimpleSchema.Integer, @@ -992,7 +1003,7 @@ describe('autoValue', function () { 'nested.$': nestedSchema, }); - const cleanedObject = schema.clean({ + const cleanedObject = await schema.clean({ $push: { nested: { doubleNested: {}, @@ -1011,7 +1022,7 @@ describe('autoValue', function () { }); }); - it('after cleaning with one extended, autoValues do not bleed over', function () { + it('after cleaning with one extended, autoValues do not bleed over', async function () { const schema1 = new SimpleSchema({ n: Number, obj: { @@ -1034,9 +1045,9 @@ describe('autoValue', function () { // {} because additional default values within that object would actually // be mutated onto the original object. We now clone autoValues in // AutoValueRunner to fix this. - expect(schema1.clean({})).to.deep.equal({ obj: {} }); - expect(schema2.clean({})).to.deep.equal({ obj: { b: 1 } }); - expect(schema1.clean({})).to.deep.equal({ obj: {} }); - expect(schema2.clean({})).to.deep.equal({ obj: { b: 1 } }); + expect(await schema1.clean({})).to.deep.equal({ obj: {} }); + expect(await schema2.clean({})).to.deep.equal({ obj: { b: 1 } }); + expect(await schema1.clean({})).to.deep.equal({ obj: {} }); + expect(await schema2.clean({})).to.deep.equal({ obj: { b: 1 } }); }); }); diff --git a/lib/clean/defaultValue.tests.js b/lib/clean/defaultValue.tests.js index 730e503..adca8e5 100644 --- a/lib/clean/defaultValue.tests.js +++ b/lib/clean/defaultValue.tests.js @@ -5,7 +5,7 @@ import { SimpleSchema } from '../SimpleSchema'; describe('defaultValue', function () { describe('normal objects', function () { - it('adds default value for missing top-level simple prop', function () { + it('adds default value for missing top-level simple prop', async function () { const schema = new SimpleSchema({ name: { type: String, @@ -14,12 +14,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({}); + const result = await schema.clean({}); expect(result).to.deep.equal({ name: 'Test' }); }); - it('does not add default value for already set top-level simple prop', function () { + it('does not add default value for already set top-level simple prop', async function () { const schema = new SimpleSchema({ name: { type: String, @@ -28,12 +28,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ name: 'Other' }); + const result = await schema.clean({ name: 'Other' }); expect(result).to.deep.equal({ name: 'Other' }); }); - it('adds default value for missing top-level array prop', function () { + it('adds default value for missing top-level array prop', async function () { const schema = new SimpleSchema({ names: { type: Array, @@ -43,12 +43,12 @@ describe('defaultValue', function () { 'names.$': String, }); - const result = schema.clean({}); + const result = await schema.clean({}); expect(result).to.deep.equal({ names: [] }); }); - it('does not add default value for top-level array prop that is already set', function () { + it('does not add default value for top-level array prop that is already set', async function () { const schema = new SimpleSchema({ names: { type: Array, @@ -58,12 +58,12 @@ describe('defaultValue', function () { 'names.$': String, }); - const result = schema.clean({ names: ['foo', 'bar'] }); + const result = await schema.clean({ names: ['foo', 'bar'] }); expect(result).to.deep.equal({ names: ['foo', 'bar'] }); }); - it('does not add defaultValue for prop in object, if object is not set', function () { + it('does not add defaultValue for prop in object, if object is not set', async function () { const schema = new SimpleSchema({ a: { type: Object, @@ -76,12 +76,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({}); + const result = await schema.clean({}); expect(result).to.deep.equal({}); }); - it('adds defaultValue for prop in object, if object is set in object being cleaned', function () { + it('adds defaultValue for prop in object, if object is set in object being cleaned', async function () { const schema = new SimpleSchema({ a: { type: Object, @@ -94,12 +94,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ a: {} }); + const result = await schema.clean({ a: {} }); expect(result).to.deep.equal({ a: { b: 'Test' } }); }); - it('adds defaultValue for prop in objects within array, if object is set in object being cleaned', function () { + it('adds defaultValue for prop in objects within array, if object is set in object being cleaned', async function () { const schema = new SimpleSchema({ b: { type: Array, @@ -115,12 +115,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ b: [{}, {}] }); + const result = await schema.clean({ b: [{}, {}] }); expect(result).to.deep.equal({ b: [{ a: 'Test' }, { a: 'Test' }] }); }); - it('does not add defaultValue for prop in objects within array, if the prop is already set in object being cleaned', function () { + it('does not add defaultValue for prop in objects within array, if the prop is already set in object being cleaned', async function () { const schema = new SimpleSchema({ b: { type: Array, @@ -136,12 +136,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ b: [{ a: 'Other' }] }); + const result = await schema.clean({ b: [{ a: 'Other' }] }); expect(result).to.deep.equal({ b: [{ a: 'Other' }] }); }); - it('adds defaultValue for prop in objects within array, if array and object are set by array defaultValue', function () { + it('adds defaultValue for prop in objects within array, if array and object are set by array defaultValue', async function () { const schema = new SimpleSchema({ b: { type: Array, @@ -158,12 +158,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({}); + const result = await schema.clean({}); expect(result).to.deep.equal({ b: [{ a: 'Test' }, { a: 'Other' }] }); }); - it('adds defaultValue for prop in object, if object is set by another defaultValue', function () { + it('adds defaultValue for prop in object, if object is set by another defaultValue', async function () { const schema = new SimpleSchema({ a: { type: Object, @@ -177,12 +177,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({}); + const result = await schema.clean({}); expect(result).to.deep.equal({ a: { b: 'Test' } }); }); - it('does not add defaultValue for prop in object, if prop already has value in object being cleaned', function () { + it('does not add defaultValue for prop in object, if prop already has value in object being cleaned', async function () { const schema = new SimpleSchema({ a: { type: Object, @@ -195,12 +195,12 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ a: { b: 'Other' } }); + const result = await schema.clean({ a: { b: 'Other' } }); expect(result).to.deep.equal({ a: { b: 'Other' } }); }); - it('adds boolean true default value', function () { + it('adds boolean true default value', async function () { const schema = new SimpleSchema({ bool: { type: Boolean, @@ -208,11 +208,11 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({}); + const result = await schema.clean({}); expect(result).to.deep.equal({ bool: true }); }); - it('adds boolean false default value', function () { + it('adds boolean false default value', async function () { const schema = new SimpleSchema({ bool: { type: Boolean, @@ -220,13 +220,13 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({}); + const result = await schema.clean({}); expect(result).to.deep.equal({ bool: false }); }); }); describe('modifier object', function () { - it('adds to $set object', function () { + it('adds to $set object', async function () { const schema = new SimpleSchema({ obj: { type: Object, @@ -242,7 +242,7 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ + const result = await schema.clean({ $set: { obj: { a: 1 }, }, @@ -255,7 +255,7 @@ describe('defaultValue', function () { }); }); - it('adds to $set object with dotted set prop', function () { + it('adds to $set object with dotted set prop', async function () { const schema = new SimpleSchema({ obj: { type: Object, @@ -276,14 +276,17 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ - $set: { - 'obj.a': {}, + const result = await schema.clean( + { + $set: { + 'obj.a': {}, + }, }, - }, { - isModifier: true, - isUpsert: true, - }); + { + isModifier: true, + isUpsert: true, + }, + ); expect(result).to.deep.equal({ $set: { @@ -295,7 +298,7 @@ describe('defaultValue', function () { }); }); - it('adds to $set object with dotted set prop and array', function () { + it('adds to $set object with dotted set prop and array', async function () { const schema = new SimpleSchema({ obj: { type: Object, @@ -316,7 +319,7 @@ describe('defaultValue', function () { }, }); - let result = schema.clean({ + let result = await schema.clean({ $set: { 'obj.a': {}, }, @@ -328,7 +331,7 @@ describe('defaultValue', function () { }, }); - result = schema.clean({ + result = await schema.clean({ $set: { 'obj.a': { foo: [] }, }, @@ -340,7 +343,7 @@ describe('defaultValue', function () { }, }); - result = schema.clean({ + result = await schema.clean({ $set: { 'obj.a': { foo: [{}, {}] }, }, @@ -353,7 +356,7 @@ describe('defaultValue', function () { }); }); - it('adds a $setOnInsert if $setting a sibling prop', function () { + it('adds a $setOnInsert if $setting a sibling prop', async function () { const schema = new SimpleSchema({ obj: { type: Object, @@ -374,15 +377,18 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ - $set: { - 'obj.a': 100, - 'obj.c': 2, + const result = await schema.clean( + { + $set: { + 'obj.a': 100, + 'obj.c': 2, + }, }, - }, { - isModifier: true, - isUpsert: true, - }); + { + isModifier: true, + isUpsert: true, + }, + ); expect(result).to.deep.equal({ $set: { @@ -395,7 +401,7 @@ describe('defaultValue', function () { }); }); - it('adds a $setOnInsert if $setting a sibling child prop', function () { + it('adds a $setOnInsert if $setting a sibling child prop', async function () { const schema = new SimpleSchema({ obj: { type: Object, @@ -426,14 +432,17 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ - $set: { - 'obj.a.one': 100, + const result = await schema.clean( + { + $set: { + 'obj.a.one': 100, + }, }, - }, { - isModifier: true, - isUpsert: true, - }); + { + isModifier: true, + isUpsert: true, + }, + ); expect(result).to.deep.equal({ $set: { @@ -447,7 +456,7 @@ describe('defaultValue', function () { }); }); - it('adds $setOnInsert for top-level prop', function () { + it('adds $setOnInsert for top-level prop', async function () { const schema = new SimpleSchema({ foo: { type: String, @@ -462,14 +471,17 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ - $addToSet: { - names: 'new value', + const result = await schema.clean( + { + $addToSet: { + names: 'new value', + }, }, - }, { - isModifier: true, - isUpsert: true, - }); + { + isModifier: true, + isUpsert: true, + }, + ); expect(result).to.deep.equal({ $addToSet: { @@ -481,7 +493,7 @@ describe('defaultValue', function () { }); }); - it('adds default values to object being $pushed into array', function () { + it('adds default values to object being $pushed into array', async function () { const schema = new SimpleSchema({ things: Array, 'things.$': Object, @@ -495,7 +507,7 @@ describe('defaultValue', function () { }, }); - const result = schema.clean({ + const result = await schema.clean({ $push: { things: {}, }, @@ -512,7 +524,7 @@ describe('defaultValue', function () { }); }); - it('nested defaultValue for prop in obj in array', function () { + it('nested defaultValue for prop in obj in array', async function () { const listItemSchema = new SimpleSchema({ foo: { type: String, @@ -537,7 +549,7 @@ describe('defaultValue', function () { }, }); - const cleanedObject = schema.clean({ + const cleanedObject = await schema.clean({ name: 'NAME', details: {}, }); @@ -548,7 +560,7 @@ describe('defaultValue', function () { }); }); - it('issue 426', function () { + it('issue 426', async function () { const schema = new SimpleSchema({ name: { type: String, @@ -568,13 +580,13 @@ describe('defaultValue', function () { const doc = { name: 'Test', }; - expect(schema.clean(doc)).to.deep.equal({ + expect(await schema.clean(doc)).to.deep.equal({ name: 'Test', images: [], }); }); - it('complex with .$. modifier', () => { + it('complex with .$. modifier', async () => { const fooSchema = new SimpleSchema({ bar: { type: String, @@ -600,7 +612,7 @@ describe('defaultValue', function () { }, }); - let result = schema.clean({ + let result = await schema.clean({ $set: { 'items.$.foo': { bar: 'OTHER' }, }, @@ -612,7 +624,7 @@ describe('defaultValue', function () { }, }); - result = schema.clean({ + result = await schema.clean({ $addToSet: { items: { foo: { bar: 'OTHER' }, @@ -629,7 +641,7 @@ describe('defaultValue', function () { }); }); - it('$setOnInsert are correctly added with path notation', function () { + it('$setOnInsert are correctly added with path notation', async function () { const schema = new SimpleSchema({ settings: { type: Object, @@ -668,17 +680,22 @@ describe('defaultValue', function () { 'settings.obj2.name': String, }); - expect(schema.clean({ - $set: { - 'settings.obj.bool': true, - }, - $unset: { - 'settings.obj2.name': '', - }, - }, { - isModifier: true, - isUpsert: true, - })).to.deep.equal({ + expect( + await schema.clean( + { + $set: { + 'settings.obj.bool': true, + }, + $unset: { + 'settings.obj2.name': '', + }, + }, + { + isModifier: true, + isUpsert: true, + }, + ), + ).to.deep.equal({ $set: { 'settings.obj.bool': true, }, @@ -693,7 +710,7 @@ describe('defaultValue', function () { }); }); - it('$setOnInsert are correctly added with path notation - v2', function () { + it('$setOnInsert are correctly added with path notation - v2', async function () { // This is the same as the test above, except that there is no default // value of {} for settings.obj2 so settings.obj2.bool should not be // set on insert @@ -734,17 +751,22 @@ describe('defaultValue', function () { 'settings.obj2.name': String, }); - expect(schema.clean({ - $set: { - 'settings.obj.bool': true, - }, - $unset: { - 'settings.obj2.name': '', - }, - }, { - isModifier: true, - isUpsert: true, - })).to.deep.equal({ + expect( + await schema.clean( + { + $set: { + 'settings.obj.bool': true, + }, + $unset: { + 'settings.obj2.name': '', + }, + }, + { + isModifier: true, + isUpsert: true, + }, + ), + ).to.deep.equal({ $set: { 'settings.obj.bool': true, }, @@ -758,7 +780,7 @@ describe('defaultValue', function () { }); }); - it('default value for sibling field added by $addToSet', function () { + it('default value for sibling field added by $addToSet', async function () { const AddressItem = new SimpleSchema({ fullName: String, address1: String, @@ -796,7 +818,7 @@ describe('defaultValue', function () { }, }; - const cleanedModifier = schema.clean(accountsUpdateQuery, { isModifier: true, isUpsert: true }); + const cleanedModifier = await schema.clean(accountsUpdateQuery, { isModifier: true, isUpsert: true }); expect(cleanedModifier).to.deep.equal({ $addToSet: { 'profile.addressBook': { @@ -811,33 +833,43 @@ describe('defaultValue', function () { }); }); - it('does not add $setOnInsert to modifiers normally', function () { + it('does not add $setOnInsert to modifiers normally', async function () { const schema = new SimpleSchema({ name: String, isOwner: { type: Boolean, defaultValue: true }, }); - expect(schema.clean({ - $set: { name: 'Phil' }, - }, { - isModifier: true, - })).to.deep.equal({ + expect( + await schema.clean( + { + $set: { name: 'Phil' }, + }, + { + isModifier: true, + }, + ), + ).to.deep.equal({ $set: { name: 'Phil' }, }); }); - it('adds $setOnInsert to modifiers when isUpsert it true', function () { + it('adds $setOnInsert to modifiers when isUpsert it true', async function () { const schema = new SimpleSchema({ name: String, isOwner: { type: Boolean, defaultValue: true }, }); - expect(schema.clean({ - $set: { name: 'Phil' }, - }, { - isModifier: true, - isUpsert: true, - })).to.deep.equal({ + expect( + await schema.clean( + { + $set: { name: 'Phil' }, + }, + { + isModifier: true, + isUpsert: true, + }, + ), + ).to.deep.equal({ $set: { name: 'Phil' }, $setOnInsert: { isOwner: true }, }); From 490867000a3c8a666a02e8fc3dd6e98cef86ba93 Mon Sep 17 00:00:00 2001 From: Victor Parpoil Date: Thu, 16 Jan 2025 14:47:30 +0100 Subject: [PATCH 3/6] fix: add describe and it as globals for standardx to avoid bad outputs in lint --- tests/package.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/package.json b/tests/package.json index eee86b3..47509dd 100644 --- a/tests/package.json +++ b/tests/package.json @@ -43,7 +43,9 @@ "arrayTracker", "globalDefaultTemplate", "defaultTypeTemplates", - "deps" + "deps", + "describe", + "it" ], "ignore": [ "**/tests/" From f499f65a49fb19c39e979a0cf9783ee2af84fb15 Mon Sep 17 00:00:00 2001 From: Victor Parpoil Date: Thu, 16 Jan 2025 14:48:07 +0100 Subject: [PATCH 4/6] fix: update package lock --- tests/package-lock.json | 328 +++++++++++++--------------------------- 1 file changed, 106 insertions(+), 222 deletions(-) diff --git a/tests/package-lock.json b/tests/package-lock.json index 5eae35d..b1a7ec1 100644 --- a/tests/package-lock.json +++ b/tests/package-lock.json @@ -43,11 +43,13 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.24.2", + "version": "7.26.2", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", + "integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/highlight": "^7.24.2", + "@babel/helper-validator-identifier": "^7.25.9", + "js-tokens": "^4.0.0", "picocolors": "^1.0.0" }, "engines": { @@ -55,9 +57,10 @@ } }, "node_modules/@babel/compat-data": { - "version": "7.24.4", + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.26.5.tgz", + "integrity": "sha512-XvcZi1KWf88RVbF9wn8MN6tYFloU5qX8KjuF3E1PVBmJ9eypXfs4GRiJwLuTZL0iSnJUKn1BFPa5BPZZJyFzPg==", "dev": true, - "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -92,9 +95,10 @@ } }, "node_modules/@babel/eslint-parser": { - "version": "7.24.1", + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.26.5.tgz", + "integrity": "sha512-Kkm8C8uxI842AwQADxl0GbcG1rupELYLShazYEZO/2DYjhyWXJIOUVOE3tBYm6JXzUCNJOZEzqc4rCW/jsEQYQ==", "dev": true, - "license": "MIT", "dependencies": { "@nicolo-ribaudo/eslint-scope-5-internals": "5.1.1-v1", "eslint-visitor-keys": "^2.1.0", @@ -105,31 +109,34 @@ }, "peerDependencies": { "@babel/core": "^7.11.0", - "eslint": "^7.5.0 || ^8.0.0" + "eslint": "^7.5.0 || ^8.0.0 || ^9.0.0" } }, "node_modules/@babel/generator": { - "version": "7.24.4", + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.5.tgz", + "integrity": "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/types": "^7.24.0", + "@babel/parser": "^7.26.5", + "@babel/types": "^7.26.5", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", - "jsesc": "^2.5.1" + "jsesc": "^3.0.2" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.23.6", + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.26.5.tgz", + "integrity": "sha512-IXuyn5EkouFJscIDuFF5EsiSolseme1s0CZB+QxVugqJLYmKdxI1VfIBOst0SUu4rnk2Z7kqTwmoO1lp3HIfnA==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/compat-data": "^7.23.5", - "@babel/helper-validator-option": "^7.23.5", - "browserslist": "^4.22.2", + "@babel/compat-data": "^7.26.5", + "@babel/helper-validator-option": "^7.25.9", + "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" }, @@ -137,58 +144,28 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/helper-environment-visitor": { - "version": "7.22.20", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-function-name": { - "version": "7.23.0", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.22.15", - "@babel/types": "^7.23.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.22.5", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@babel/helper-module-imports": { - "version": "7.24.3", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.25.9.tgz", + "integrity": "sha512-tnUA4RsrmflIM6W6RFTLFSXITtl0wKjgpnLgXyowocVPrbYrLUXSBXDgTs8BlbmIzIdlBySRQjINYs2BAkiLtw==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/types": "^7.24.0" + "@babel/traverse": "^7.25.9", + "@babel/types": "^7.25.9" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.23.3", + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.26.0.tgz", + "integrity": "sha512-xO+xu6B5K2czEnQye6BHA7DolFFmS3LB7stHZFaOLb1pAwO1HWLS8fXA+eh0A2yIvltPVmx3eNNDBJA2SLHXFw==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-module-imports": "^7.22.15", - "@babel/helper-simple-access": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/helper-validator-identifier": "^7.22.20" + "@babel/helper-module-imports": "^7.25.9", + "@babel/helper-validator-identifier": "^7.25.9", + "@babel/traverse": "^7.25.9" }, "engines": { "node": ">=6.9.0" @@ -198,55 +175,37 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.24.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-simple-access": { - "version": "7.22.5", + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.26.5.tgz", + "integrity": "sha512-RS+jZcRdZdRFzMyr+wcsaqOmld1/EqTghfaBGQQd/WnRdzdlvSZ//kF7U8VQTxf1ynZ4cjUcYgjVGx13ewNPMg==", "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-split-export-declaration": { - "version": "7.22.6", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.22.5" - }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-string-parser": { - "version": "7.24.1", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz", + "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==", "dev": true, - "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.20", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", + "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", "dev": true, - "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-option": { - "version": "7.23.5", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.25.9.tgz", + "integrity": "sha512-e/zv1co8pp55dNdEcCynfj9X7nyUKUXoUEwfXqaZt0omVOmDe9oOTdKStH4GmAw6zxMFs50ZayuMfHDKlO7Tfw==", "dev": true, - "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -264,24 +223,14 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/highlight": { - "version": "7.24.2", + "node_modules/@babel/parser": { + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.5.tgz", + "integrity": "sha512-SRJ4jYmXRqV1/Xc+TIVG84WjHBXKlxO9sHQnA2Pf12QQEAp1LOh6kDzNHXcUnbH1QI0FDoPPVOt+vyUDucxpaw==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^7.22.20", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0", - "picocolors": "^1.0.0" + "@babel/types": "^7.26.5" }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.24.4", - "dev": true, - "license": "MIT", "bin": { "parser": "bin/babel-parser.js" }, @@ -300,31 +249,30 @@ } }, "node_modules/@babel/template": { - "version": "7.24.0", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.9.tgz", + "integrity": "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.23.5", - "@babel/parser": "^7.24.0", - "@babel/types": "^7.24.0" + "@babel/code-frame": "^7.25.9", + "@babel/parser": "^7.25.9", + "@babel/types": "^7.25.9" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.24.1", + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.26.5.tgz", + "integrity": "sha512-rkOSPOw+AXbgtwUga3U4u8RpoK9FEFWBNAlTpcnkLFjL5CT+oyHNuUUC/xx6XefEJ16r38r8Bc/lfp6rYuHeJQ==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.24.1", - "@babel/generator": "^7.24.1", - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.23.0", - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.24.1", - "@babel/types": "^7.24.0", + "@babel/code-frame": "^7.26.2", + "@babel/generator": "^7.26.5", + "@babel/parser": "^7.26.5", + "@babel/template": "^7.25.9", + "@babel/types": "^7.26.5", "debug": "^4.3.1", "globals": "^11.1.0" }, @@ -333,13 +281,13 @@ } }, "node_modules/@babel/types": { - "version": "7.24.0", + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.5.tgz", + "integrity": "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^7.23.4", - "@babel/helper-validator-identifier": "^7.22.20", - "to-fast-properties": "^2.0.0" + "@babel/helper-string-parser": "^7.25.9", + "@babel/helper-validator-identifier": "^7.25.9" }, "engines": { "node": ">=6.9.0" @@ -709,17 +657,6 @@ "node": ">=8" } }, - "node_modules/ansi-styles": { - "version": "3.2.1", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/append-transform": { "version": "2.0.0", "dev": true, @@ -977,7 +914,9 @@ } }, "node_modules/browserslist": { - "version": "4.23.0", + "version": "4.24.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.4.tgz", + "integrity": "sha512-KDi1Ny1gSePi1vm0q4oxSF8b4DR44GF4BbmS2YdhPLOEqd8pDviZOGH/GsmRwoWJ2+5Lr085X7naowMwKHDG1A==", "dev": true, "funding": [ { @@ -993,12 +932,11 @@ "url": "https://github.com/sponsors/ai" } ], - "license": "MIT", "dependencies": { - "caniuse-lite": "^1.0.30001587", - "electron-to-chromium": "^1.4.668", - "node-releases": "^2.0.14", - "update-browserslist-db": "^1.0.13" + "caniuse-lite": "^1.0.30001688", + "electron-to-chromium": "^1.5.73", + "node-releases": "^2.0.19", + "update-browserslist-db": "^1.1.1" }, "bin": { "browserslist": "cli.js" @@ -1092,7 +1030,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001611", + "version": "1.0.30001692", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001692.tgz", + "integrity": "sha512-A95VKan0kdtrsnMubMKxEKUKImOPSuCpYgxSQBo036P5YYgVIcOYJEgt/txJWqObiRQeISNCfef9nvlQ0vbV7A==", "dev": true, "funding": [ { @@ -1107,8 +1047,7 @@ "type": "github", "url": "https://github.com/sponsors/ai" } - ], - "license": "CC-BY-4.0" + ] }, "node_modules/chai": { "version": "5.1.0", @@ -1125,19 +1064,6 @@ "node": ">=12" } }, - "node_modules/chalk": { - "version": "2.4.2", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/check-error": { "version": "2.0.0", "dev": true, @@ -1177,19 +1103,6 @@ "wrap-ansi": "^6.2.0" } }, - "node_modules/color-convert": { - "version": "1.9.3", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/color-name": { - "version": "1.1.3", - "dev": true, - "license": "MIT" - }, "node_modules/commondir": { "version": "1.0.1", "dev": true, @@ -1467,9 +1380,10 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.4.740", - "dev": true, - "license": "ISC" + "version": "1.5.83", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.83.tgz", + "integrity": "sha512-LcUDPqSt+V0QmI47XLzZrz5OqILSMGsPFkDYus22rIbgorSvBYEFqq854ltTmUdHkY92FSdAAvsh4jWEULMdfQ==", + "dev": true }, "node_modules/emoji-regex": { "version": "8.0.0", @@ -1644,21 +1558,14 @@ "license": "MIT" }, "node_modules/escalade": { - "version": "3.1.2", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", "dev": true, - "license": "MIT", "engines": { "node": ">=6" } }, - "node_modules/escape-string-regexp": { - "version": "1.0.5", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.0" - } - }, "node_modules/escodegen": { "version": "2.1.0", "dev": true, @@ -2685,14 +2592,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/has-flag": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, "node_modules/has-property-descriptors": { "version": "1.0.2", "dev": true, @@ -3348,14 +3247,15 @@ "license": "MIT" }, "node_modules/jsesc": { - "version": "2.5.2", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", "dev": true, - "license": "MIT", "bin": { "jsesc": "bin/jsesc" }, "engines": { - "node": ">=4" + "node": ">=6" } }, "node_modules/json-buffer": { @@ -4733,9 +4633,10 @@ } }, "node_modules/node-releases": { - "version": "2.0.14", - "dev": true, - "license": "MIT" + "version": "2.0.19", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz", + "integrity": "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==", + "dev": true }, "node_modules/normalize-package-data": { "version": "2.5.0", @@ -5115,9 +5016,10 @@ "license": "MIT" }, "node_modules/picocolors": { - "version": "1.0.0", - "dev": true, - "license": "ISC" + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true }, "node_modules/pify": { "version": "3.0.0", @@ -6288,17 +6190,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/supports-color": { - "version": "5.5.0", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/supports-preserve-symlinks-flag": { "version": "1.0.0", "dev": true, @@ -6399,14 +6290,6 @@ "dev": true, "license": "MIT" }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, "node_modules/tsconfig-paths": { "version": "3.15.0", "dev": true, @@ -6594,7 +6477,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.0.13", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.2.tgz", + "integrity": "sha512-PPypAm5qvlD7XMZC3BujecnaOxwhrtoFR+Dqkk5Aa/6DssiH0ibKoketaj9w8LP7Bont1rYeoV5plxD7RTEPRg==", "dev": true, "funding": [ { @@ -6610,10 +6495,9 @@ "url": "https://github.com/sponsors/ai" } ], - "license": "MIT", "dependencies": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" + "escalade": "^3.2.0", + "picocolors": "^1.1.1" }, "bin": { "update-browserslist-db": "cli.js" From f62db326f9ab4999b2f2b17b76c3bd097ad615db Mon Sep 17 00:00:00 2001 From: Victor Parpoil Date: Thu, 16 Jan 2025 14:48:53 +0100 Subject: [PATCH 5/6] fix: add .DS_Store to ignore --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8be7f0c..f01bad7 100644 --- a/.gitignore +++ b/.gitignore @@ -106,4 +106,6 @@ dist # IDE specific .idea .vscode -.atom \ No newline at end of file +.atom + +.DS_Store From 33ba518468847973f2ea5361e8284ec840dc8302 Mon Sep 17 00:00:00 2001 From: Victor Parpoil Date: Thu, 16 Jan 2025 14:49:12 +0100 Subject: [PATCH 6/6] fix: meteor npm run lint:fix All errors are fixed expect some regarding lib/SimpleSchema.js and its class fields and static properties which are recents syntax updates --- lib/SimpleSchema.js | 75 +- lib/SimpleSchema.tests.js | 1112 +++++----- lib/SimpleSchemaGroup.js | 34 +- lib/SimpleSchema_allowedValues.tests.js | 364 ++-- lib/SimpleSchema_autoValueFunctions.tests.js | 180 +- lib/SimpleSchema_blackbox.tests.js | 58 +- lib/SimpleSchema_custom.tests.js | 174 +- lib/SimpleSchema_definition.tests.js | 30 +- lib/SimpleSchema_extend.tests.js | 260 +-- lib/SimpleSchema_getObjectSchema.tests.js | 102 +- lib/SimpleSchema_getQuickTypeForKey.tests.js | 144 +- lib/SimpleSchema_labels.tests.js | 72 +- lib/SimpleSchema_max.tests.js | 360 ++-- lib/SimpleSchema_messages.tests.js | 326 +-- lib/SimpleSchema_min.tests.js | 280 +-- lib/SimpleSchema_minCount.tests.js | 24 +- lib/SimpleSchema_namedContext.tests.js | 38 +- lib/SimpleSchema_omit.tests.js | 28 +- lib/SimpleSchema_oneOf.tests.js | 188 +- lib/SimpleSchema_pick.tests.js | 38 +- lib/SimpleSchema_regEx.tests.js | 452 ++-- lib/SimpleSchema_required.tests.js | 562 ++--- lib/SimpleSchema_rules.tests.js | 28 +- lib/SimpleSchema_type.tests.js | 1856 ++++++++--------- lib/ValidationContext.js | 138 +- lib/clean.js | 164 +- lib/clean.tests.js | 844 ++++---- lib/clean/AutoValueRunner.js | 84 +- lib/clean/autoValue.tests.js | 982 ++++----- lib/clean/convertToProperType.js | 40 +- lib/clean/convertToProperType.tests.js | 38 +- lib/clean/defaultValue.tests.js | 674 +++--- lib/clean/getPositionsForAutoValue.js | 66 +- lib/clean/setAutoValues.js | 34 +- lib/clean/setAutoValues.tests.js | 50 +- lib/defaultMessages.js | 28 +- lib/doValidation.js | 264 +-- lib/expandShorthand.js | 42 +- lib/expandShorthand.tests.js | 40 +- lib/humanize.js | 54 +- lib/humanize.tests.js | 38 +- lib/main.js | 8 +- lib/reactivity.tests.js | 126 +- lib/regExp.js | 48 +- lib/testHelpers/Address.js | 32 +- lib/testHelpers/expectErrorLength.js | 8 +- lib/testHelpers/expectErrorOfTypeLength.js | 16 +- lib/testHelpers/expectRequiredErrorLength.js | 18 +- lib/testHelpers/expectValid.js | 8 +- lib/testHelpers/friendsSchema.js | 36 +- lib/testHelpers/optionalCustomSchema.js | 10 +- lib/testHelpers/requiredCustomSchema.js | 24 +- lib/testHelpers/requiredSchema.js | 40 +- lib/testHelpers/testSchema.js | 126 +- lib/testHelpers/validate.js | 8 +- lib/utility/appendAffectedKey.js | 6 +- lib/utility/dateToDateString.js | 12 +- lib/utility/forEachKeyAncestor.js | 16 +- lib/utility/getKeysWithValueInObj.js | 18 +- lib/utility/getLastPartOfKey.js | 12 +- lib/utility/getLastPartOfKey.tests.js | 14 +- lib/utility/getParentOfKey.js | 6 +- lib/utility/index.js | 20 +- lib/utility/isEmptyObject.js | 6 +- lib/utility/isObjectWeShouldTraverse.js | 28 +- lib/utility/looksLikeModifier.js | 4 +- lib/utility/merge.js | 22 +- lib/validation/allowedValuesValidator.js | 18 +- lib/validation/requiredValidator.js | 38 +- lib/validation/typeValidator/doArrayChecks.js | 10 +- lib/validation/typeValidator/doDateChecks.js | 12 +- .../typeValidator/doNumberChecks.js | 18 +- .../typeValidator/doStringChecks.js | 28 +- lib/validation/typeValidator/index.js | 58 +- package.js | 24 +- 75 files changed, 5623 insertions(+), 5620 deletions(-) diff --git a/lib/SimpleSchema.js b/lib/SimpleSchema.js index 3c6466e..b423042 100644 --- a/lib/SimpleSchema.js +++ b/lib/SimpleSchema.js @@ -12,14 +12,7 @@ import { forEachKeyAncestor, isEmptyObject, merge } from './utility'; import defaultMessages from './defaultMessages'; // Exported for tests -export const schemaDefinitionOptions = [ - 'autoValue', - 'defaultValue', - 'label', - 'optional', - 'required', - 'type', -]; +export const schemaDefinitionOptions = ['autoValue', 'defaultValue', 'label', 'optional', 'required', 'type']; const oneOfProps = [ 'allowedValues', @@ -53,7 +46,7 @@ const propsThatCanBeFunction = [ class SimpleSchema { constructor(schema = {}, options = {}) { - // Stash the options object + // [...Stash the options object this._constructorOptions = { ...SimpleSchema._constructorOptionDefaults, ...options, @@ -88,8 +81,8 @@ class SimpleSchema { } /** - /* @returns {Object} The entire raw schema definition passed in the constructor - */ + /* @returns {Object} The entire raw schema definition passed in the constructor + */ get rawDefinition() { return this._rawDefinition; } @@ -114,7 +107,7 @@ class SimpleSchema { * @returns {Boolean} True if the given object appears to be a SimpleSchema instance */ static isSimpleSchema(obj) { - return (obj && (obj instanceof SimpleSchema || obj._schema)); + return obj && (obj instanceof SimpleSchema || obj._schema); } /** @@ -222,7 +215,7 @@ class SimpleSchema { mergedSchema[key] = keySchema; keySchema.type.definitions.forEach((typeDef) => { - if (!(SimpleSchema.isSimpleSchema(typeDef.type))) return; + if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; const childSchema = typeDef.type.mergedSchema(); Object.keys(childSchema).forEach((subKey) => { mergedSchema[`${key}.${subKey}`] = childSchema[subKey]; @@ -256,7 +249,8 @@ class SimpleSchema { ...functionContext, }); // Inflect label if undefined - if (prop === 'label' && typeof newObj[prop] !== 'string') newObj[prop] = inflectedLabel(key, this._constructorOptions.humanizeAutoLabels); + if (prop === 'label' && typeof newObj[prop] !== 'string') + newObj[prop] = inflectedLabel(key, this._constructorOptions.humanizeAutoLabels); } else { newObj[prop] = val; } @@ -355,18 +349,16 @@ class SimpleSchema { this._schemaKeys.forEach((key) => { this._schema[key].type.definitions.forEach((typeDef) => { - if (!(SimpleSchema.isSimpleSchema(typeDef.type))) return; - result = result.concat(typeDef.type.autoValueFunctions().map(({ - func, - fieldName, - closestSubschemaFieldName, - }) => { - return { - func, - fieldName: `${key}.${fieldName}`, - closestSubschemaFieldName: closestSubschemaFieldName.length ? `${key}.${closestSubschemaFieldName}` : key, - }; - })); + if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; + result = result.concat( + typeDef.type.autoValueFunctions().map(({ func, fieldName, closestSubschemaFieldName }) => { + return { + func, + fieldName: `${key}.${fieldName}`, + closestSubschemaFieldName: closestSubschemaFieldName.length ? `${key}.${closestSubschemaFieldName}` : key, + }; + }), + ); }); }); @@ -379,7 +371,7 @@ class SimpleSchema { this._schemaKeys.forEach((key) => { this._schema[key].type.definitions.forEach((typeDef) => { - if (!(SimpleSchema.isSimpleSchema(typeDef.type))) return; + if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; typeDef.type.blackboxKeys().forEach((blackboxKey) => { blackboxKeys.add(`${key}.${blackboxKey}`); }); @@ -399,7 +391,7 @@ class SimpleSchema { const testKeySchema = this.schema(ancestor); if (testKeySchema) { testKeySchema.type.definitions.forEach((typeDef) => { - if (!(SimpleSchema.isSimpleSchema(typeDef.type))) return; + if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; if (typeDef.type.keyIsInBlackBox(remainder)) isInBlackBox = true; }); } @@ -437,7 +429,7 @@ class SimpleSchema { let allowed = false; const subKey = key.slice(loopKey.length + 1); fieldSchema.type.definitions.forEach((typeDef) => { - if (!(SimpleSchema.isSimpleSchema(typeDef.type))) return; + if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; if (typeDef.type.allowsKey(subKey)) allowed = true; }); return allowed; @@ -568,7 +560,8 @@ class SimpleSchema { // Make sure parent has a definition in the schema. No implied objects! if (fieldName.indexOf('.') > -1) { const parentFieldName = fieldName.slice(0, fieldName.lastIndexOf('.')); - if (!Object.prototype.hasOwnProperty.call(this._schema, parentFieldName)) throw new Error(`"${fieldName}" is in the schema but "${parentFieldName}" is not`); + if (!Object.prototype.hasOwnProperty.call(this._schema, parentFieldName)) + throw new Error(`"${fieldName}" is in the schema but "${parentFieldName}" is not`); } const definition = this._schema[fieldName]; @@ -657,7 +650,11 @@ class SimpleSchema { const check = options.check || this._constructorOptions.check; if (typeof check === 'function') { // Call check but ignore the error - try { check(obj); } catch (e) { /* ignore error */ } + try { + check(obj); + } catch (e) { + /* ignore error */ + } } // obj can be an array, in which case we validate each object in it and @@ -717,7 +714,7 @@ class SimpleSchema { } validator(options = {}) { - return async(obj) => { + return async (obj) => { const optionsClone = { ...options }; if (options.clean === true) { // Do this here and pass into both functions for better performance @@ -855,7 +852,7 @@ class SimpleSchema { static validate(obj, schema, options) { // Allow passing just the schema object - if (!(SimpleSchema.isSimpleSchema(schema))) { + if (!SimpleSchema.isSimpleSchema(schema)) { schema = new SimpleSchema(schema); } @@ -957,12 +954,14 @@ function checkSchemaOverlap(schema) { const val = schema[key]; if (!val.type) throw new Error(`${key} key is missing "type"`); val.type.definitions.forEach((def) => { - if (!(SimpleSchema.isSimpleSchema(def.type))) return; + if (!SimpleSchema.isSimpleSchema(def.type)) return; Object.keys(def.type._schema).forEach((subKey) => { const newKey = `${key}.${subKey}`; if (Object.prototype.hasOwnProperty.call(schema, newKey)) { - throw new Error(`The type for "${key}" is set to a SimpleSchema instance that defines "${key}.${subKey}", but the parent SimpleSchema instance also tries to define "${key}.${subKey}"`); + throw new Error( + `The type for "${key}" is set to a SimpleSchema instance that defines "${key}.${subKey}", but the parent SimpleSchema instance also tries to define "${key}.${subKey}"`, + ); } }); }); @@ -1069,7 +1068,9 @@ function checkAndScrubDefinition(fieldName, definition, options, allKeys) { Object.keys(type._schema).forEach((subKey) => { const newKey = `${fieldName}.${subKey}`; if (allKeys.has(newKey)) { - throw new Error(`The type for "${fieldName}" is set to a SimpleSchema instance that defines "${newKey}", but the parent SimpleSchema instance also tries to define "${newKey}"`); + throw new Error( + `The type for "${fieldName}" is set to a SimpleSchema instance that defines "${newKey}", but the parent SimpleSchema instance also tries to define "${newKey}"`, + ); } }); } @@ -1113,7 +1114,7 @@ function checkAndScrubDefinition(fieldName, definition, options, allKeys) { definition.optional = !definition.required; } } else { - definition.optional = (options.requiredByDefault === false); + definition.optional = options.requiredByDefault === false; } } diff --git a/lib/SimpleSchema.tests.js b/lib/SimpleSchema.tests.js index ec3cbe0..1ee96ba 100644 --- a/lib/SimpleSchema.tests.js +++ b/lib/SimpleSchema.tests.js @@ -1,169 +1,169 @@ /* eslint-disable func-names, prefer-arrow-callback, class-methods-use-this */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; -import testSchema from './testHelpers/testSchema'; -import expectValid from './testHelpers/expectValid'; -import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' +import testSchema from './testHelpers/testSchema' +import expectValid from './testHelpers/expectValid' +import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength' class CustomObject { - constructor(obj) { - Object.assign(this, obj); + constructor (obj) { + Object.assign(this, obj) } - bar() { - return 20; + bar () { + return 20 } } describe('SimpleSchema', function () { it('throws error if first argument is an array', function () { expect(function () { - return new SimpleSchema([]); - }).to.throw('You may not pass an array of schemas to the SimpleSchema constructor or to extend()'); - }); + return new SimpleSchema([]) + }).to.throw('You may not pass an array of schemas to the SimpleSchema constructor or to extend()') + }) it('throws error if a key is missing type', function () { expect(function () { return new SimpleSchema({ - foo: {}, - }); - }).to.throw('Invalid definition for foo field: "type" option is required'); - }); + foo: {} + }) + }).to.throw('Invalid definition for foo field: "type" option is required') + }) it('throws an explicit error if you define fields that override object methods', function () { expect(function () { return new SimpleSchema({ valueOf: { - type: String, - }, - }); - }).to.throw('valueOf key is actually the name of a method on Object'); - }); + type: String + } + }) + }).to.throw('valueOf key is actually the name of a method on Object') + }) it('throws a error if array item definition is missing', function () { expect(function () { return new SimpleSchema({ - someArray: Array, - }); - }).to.throw('"someArray" is Array type but the schema does not include a "someArray.$" definition for the array items'); - }); + someArray: Array + }) + }).to.throw('"someArray" is Array type but the schema does not include a "someArray.$" definition for the array items') + }) it('does not allow prototype pollution', function () { - const obj = {}; - expect(obj.polluted).to.equal(undefined); - const badObj = JSON.parse('{"__proto__":{"polluted":"yes"}}'); - SimpleSchema.setDefaultMessages(badObj); - expect(obj.polluted).to.equal(undefined); - }); + const obj = {} + expect(obj.polluted).to.equal(undefined) + const badObj = JSON.parse('{"__proto__":{"polluted":"yes"}}') + SimpleSchema.setDefaultMessages(badObj) + expect(obj.polluted).to.equal(undefined) + }) describe('nesting', function () { it('throws an error if a nested schema defines a field that its parent also defines', function () { expect(function () { return new SimpleSchema({ foo: new SimpleSchema({ - bar: String, + bar: String }), - 'foo.bar': String, - }); - }).to.throw(); - }); + 'foo.bar': String + }) + }).to.throw() + }) it('expects a field with SimpleSchema type to be an object', function () { const schema = new SimpleSchema({ foo: new SimpleSchema({ - bar: String, - }), - }); + bar: String + }) + }) - const context = schema.newContext(); + const context = schema.newContext() context.validate({ - foo: 'string', - }); + foo: 'string' + }) expect(context.validationErrors()).to.deep.equal([ { dataType: 'Object', name: 'foo', type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, - value: 'string', - }, - ]); - }); + value: 'string' + } + ]) + }) it('includes type validation errors from nested schemas', function () { const schema = new SimpleSchema({ foo: new SimpleSchema({ - bar: String, - }), - }); + bar: String + }) + }) - const context = schema.newContext(); + const context = schema.newContext() context.validate({ foo: { - bar: 12345, - }, - }); + bar: 12345 + } + }) expect(context.validationErrors()).to.deep.equal([ { dataType: 'String', name: 'foo.bar', type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, - value: 12345, - }, - ]); - }); + value: 12345 + } + ]) + }) it('includes allowed value validation errors from nested schemas', function () { const schema = new SimpleSchema({ foo: new SimpleSchema({ bar: { type: String, - allowedValues: ['hot'], - }, - }), - }); + allowedValues: ['hot'] + } + }) + }) - const context = schema.newContext(); + const context = schema.newContext() context.validate({ foo: { - bar: 'cold', - }, - }); + bar: 'cold' + } + }) expect(context.validationErrors()).to.deep.equal([ { name: 'foo.bar', type: SimpleSchema.ErrorTypes.VALUE_NOT_ALLOWED, - value: 'cold', - }, - ]); - }); + value: 'cold' + } + ]) + }) it('includes validation errors from nested schemas when validating modifiers', function () { const schema = new SimpleSchema({ foo: new SimpleSchema({ - bar: String, - }), - }); + bar: String + }) + }) - const context = schema.newContext(); + const context = schema.newContext() context.validate({ $set: { - 'foo.bar': 12345, - }, - }, { modifier: true }); + 'foo.bar': 12345 + } + }, { modifier: true }) expect(context.validationErrors()).to.deep.equal([ { dataType: 'String', name: 'foo.bar', type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, - value: 12345, - }, - ]); - }); + value: 12345 + } + ]) + }) it('validates nested requiredness', function () { const schema = new SimpleSchema({ @@ -172,464 +172,464 @@ describe('SimpleSchema', function () { b: { type: new SimpleSchema({ c: { - type: String, - }, - }), - }, - }), - }, - }); + type: String + } + }) + } + }) + } + }) - let context = schema.newContext(); - context.validate({ a: {} }); + let context = schema.newContext() + context.validate({ a: {} }) expect(context.validationErrors()).to.deep.equal([ { name: 'a.b', type: SimpleSchema.ErrorTypes.REQUIRED, - value: undefined, + value: undefined }, { name: 'a.b.c', type: SimpleSchema.ErrorTypes.REQUIRED, - value: undefined, - }, - ]); + value: undefined + } + ]) - context = schema.newContext(); - context.validate({ a: { b: {} } }); + context = schema.newContext() + context.validate({ a: { b: {} } }) expect(context.validationErrors()).to.deep.equal([ { name: 'a.b.c', type: SimpleSchema.ErrorTypes.REQUIRED, - value: undefined, - }, - ]); - }); + value: undefined + } + ]) + }) it('issue #307 - throws an error if incorrect import results in empty object', function () { expect(function () { // Assume that default import of a file with no default export returns an empty object - const Place = {}; + const Place = {} // eslint-disable-next-line no-new new SimpleSchema({ places: { type: Array, label: 'Places', - optional: true, + optional: true }, - 'places.$': { type: Place }, - }); - }).to.throw('Invalid definition for places.$ field: "type" may not be an object. Change it to Object'); - }); - }); + 'places.$': { type: Place } + }) + }).to.throw('Invalid definition for places.$ field: "type" may not be an object. Change it to Object') + }) + }) it('Safely sets defaultValues on subschemas nested in arrays', async function () { const nestedSchema = new SimpleSchema({ nested: { - type: Array, + type: Array }, 'nested.$': { type: new SimpleSchema({ somethingOptional: { type: String, - optional: true, + optional: true }, somethingAutovalued: { type: String, optional: false, - defaultValue: 'x', - }, - }), - }, - }); + defaultValue: 'x' + } + }) + } + }) - const context = nestedSchema.newContext(); + const context = nestedSchema.newContext() const cleaned = await context.clean( { $set: { - nested: [{ somethingOptional: 'q' }, { somethingOptional: 'z' }], - }, + nested: [{ somethingOptional: 'q' }, { somethingOptional: 'z' }] + } }, - { modifier: true }, - ); + { modifier: true } + ) expect(cleaned).to.deep.equal({ $set: { nested: [ { somethingAutovalued: 'x', somethingOptional: 'q' }, - { somethingAutovalued: 'x', somethingOptional: 'z' }, - ], - }, - }); - }); + { somethingAutovalued: 'x', somethingOptional: 'z' } + ] + } + }) + }) it('Issue #123', function () { // With $set const userSchema = new SimpleSchema({ profile: { - type: Object, + type: Object }, 'profile.name': { - type: String, - }, - }); + type: String + } + }) - const context = userSchema.namedContext(); + const context = userSchema.namedContext() expect(context.validate({ $set: { - profile: {}, - }, - }, { modifier: true })).to.equal(false); + profile: {} + } + }, { modifier: true })).to.equal(false) // With $push const userSchema2 = new SimpleSchema({ profile: { - type: Array, + type: Array }, 'profile.$': { - type: Object, + type: Object }, 'profile.$.name': { - type: String, - }, - }); + type: String + } + }) - const context2 = userSchema2.namedContext(); + const context2 = userSchema2.namedContext() expect(context2.validate({ $push: { - profile: {}, - }, - }, { modifier: true })).to.equal(false); - }); + profile: {} + } + }, { modifier: true })).to.equal(false) + }) it('validate object with prototype', function () { const schema = new SimpleSchema({ - foo: { type: SimpleSchema.Integer }, - }); + foo: { type: SimpleSchema.Integer } + }) - const testObj = new CustomObject({ foo: 1 }); + const testObj = new CustomObject({ foo: 1 }) - const context = schema.namedContext(); - expect(context.validate(testObj)).to.equal(true); - expect(testObj instanceof CustomObject).to.equal(true); + const context = schema.namedContext() + expect(context.validate(testObj)).to.equal(true) + expect(testObj instanceof CustomObject).to.equal(true) - testObj.foo = 'not a number'; - expect(context.validate(testObj)).to.equal(false); - }); + testObj.foo = 'not a number' + expect(context.validate(testObj)).to.equal(false) + }) it('validate object with prototype within normal object', function () { const schema = new SimpleSchema({ customObject: Object, - 'customObject.foo': SimpleSchema.Integer, - }); + 'customObject.foo': SimpleSchema.Integer + }) - const customObject = new CustomObject({ foo: 1 }); + const customObject = new CustomObject({ foo: 1 }) const testObj = { - customObject, - }; + customObject + } - const context = schema.namedContext(); - expect(context.validate(testObj)).to.equal(true); - expect(testObj.customObject instanceof CustomObject).to.equal(true); + const context = schema.namedContext() + expect(context.validate(testObj)).to.equal(true) + expect(testObj.customObject instanceof CustomObject).to.equal(true) - testObj.customObject.foo = 'not a number'; - expect(context.validate(testObj)).to.equal(false); - }); + testObj.customObject.foo = 'not a number' + expect(context.validate(testObj)).to.equal(false) + }) it('allowsKey', function () { - function run(key, allowed) { - expect(testSchema.allowsKey(key)).to.equal(allowed); + function run (key, allowed) { + expect(testSchema.allowsKey(key)).to.equal(allowed) } - run('minMaxString', true); - run('minMaxString.$', false); - run('minMaxString.$.foo', false); - run('minMaxString.$foo', false); - run('minMaxString.foo', false); - run('sub', true); - run('sub.number', true); - run('sub.number.$', false); - run('sub.number.$.foo', false); - run('sub.number.$foo', false); - run('sub.number.foo', false); - run('minMaxStringArray', true); - run('minMaxStringArray.$', true); - run('minMaxStringArray.$.foo', false); - run('minMaxStringArray.foo', false); - run('customObject', true); - run('customObject.$', false); - run('customObject.foo', true); - run('customObject.foo.$', true); - run('customObject.foo.$foo', true); - run('customObject.foo.$.$foo', true); - run('blackBoxObject', true); - run('blackBoxObject.$', false); - run('blackBoxObject.foo', true); - run('blackBoxObject.foo.$', true); - run('blackBoxObject.foo.$foo', true); - run('blackBoxObject.foo.$.$foo', true); - run('blackBoxObject.foo.bar.$.baz', true); - }); + run('minMaxString', true) + run('minMaxString.$', false) + run('minMaxString.$.foo', false) + run('minMaxString.$foo', false) + run('minMaxString.foo', false) + run('sub', true) + run('sub.number', true) + run('sub.number.$', false) + run('sub.number.$.foo', false) + run('sub.number.$foo', false) + run('sub.number.foo', false) + run('minMaxStringArray', true) + run('minMaxStringArray.$', true) + run('minMaxStringArray.$.foo', false) + run('minMaxStringArray.foo', false) + run('customObject', true) + run('customObject.$', false) + run('customObject.foo', true) + run('customObject.foo.$', true) + run('customObject.foo.$foo', true) + run('customObject.foo.$.$foo', true) + run('blackBoxObject', true) + run('blackBoxObject.$', false) + run('blackBoxObject.foo', true) + run('blackBoxObject.foo.$', true) + run('blackBoxObject.foo.$foo', true) + run('blackBoxObject.foo.$.$foo', true) + run('blackBoxObject.foo.bar.$.baz', true) + }) it('allowsKey in subschema', function () { const schema = new SimpleSchema({ foo: new SimpleSchema({ bar: Object, - 'bar.baz': String, - }), - }); + 'bar.baz': String + }) + }) - expect(schema.allowsKey('foo.bar')).to.equal(true); - expect(schema.allowsKey('foo.bar.baz')).to.equal(true); - expect(schema.allowsKey('foo.bar.bum')).to.equal(false); - expect(schema.allowsKey('foo.bar.baz.bum')).to.equal(false); - }); + expect(schema.allowsKey('foo.bar')).to.equal(true) + expect(schema.allowsKey('foo.bar.baz')).to.equal(true) + expect(schema.allowsKey('foo.bar.bum')).to.equal(false) + expect(schema.allowsKey('foo.bar.baz.bum')).to.equal(false) + }) it('validating an object with a "length" property should not error', function () { const schema = new SimpleSchema({ length: { type: Number, - optional: true, - }, - }); + optional: true + } + }) expect(() => { schema.validate({ - length: 10, - }); + length: 10 + }) schema.validate({ $set: { - length: 10, - }, - }, { modifier: true }); - }).not.to.throw(); - }); + length: 10 + } + }, { modifier: true }) + }).not.to.throw() + }) it('this.key in label function context', function () { const schema = new SimpleSchema({ items: Array, 'items.$': { type: String, - label() { - const { key } = this; - if (!key) return 'Item'; - return `Item ${key.slice(key.lastIndexOf('.') + 1)}`; - }, - }, - }); - - expect(schema.label('items.0')).to.equal('Item 0'); - expect(schema.label('items.1')).to.equal('Item 1'); - }); + label () { + const { key } = this + if (!key) return 'Item' + return `Item ${key.slice(key.lastIndexOf('.') + 1)}` + } + } + }) + + expect(schema.label('items.0')).to.equal('Item 0') + expect(schema.label('items.1')).to.equal('Item 1') + }) it('keyIsInBlackBox in subschema', function () { const schema = new SimpleSchema({ foo: new SimpleSchema({ bar: { type: Object, - blackbox: true, - }, - }), - }); + blackbox: true + } + }) + }) - expect(schema.keyIsInBlackBox('foo.bar')).to.equal(false); - expect(schema.keyIsInBlackBox('foo.bar.baz')).to.equal(true); - expect(schema.keyIsInBlackBox('foo.bar.baz.$.bum')).to.equal(true); - }); + expect(schema.keyIsInBlackBox('foo.bar')).to.equal(false) + expect(schema.keyIsInBlackBox('foo.bar.baz')).to.equal(true) + expect(schema.keyIsInBlackBox('foo.bar.baz.$.bum')).to.equal(true) + }) describe('blackboxKeys from subschema', function () { it('are correct', function () { const schema = new SimpleSchema({ apple: { type: Object, - blackbox: true, + blackbox: true }, pear: new SimpleSchema({ info: { type: Object, - blackbox: true, - }, - }), - }); + blackbox: true + } + }) + }) - expect(schema.blackboxKeys()).to.deep.equal(['apple', 'pear.info']); - }); - }); + expect(schema.blackboxKeys()).to.deep.equal(['apple', 'pear.info']) + }) + }) it('empty required array is valid', function () { const schema = new SimpleSchema({ names: { type: Array }, - 'names.$': { type: String }, - }); + 'names.$': { type: String } + }) expectValid(schema, { - names: [], - }); - }); + names: [] + }) + }) it('null in array is not valid', function () { const schema = new SimpleSchema({ names: { type: Array }, - 'names.$': { type: String }, - }); + 'names.$': { type: String } + }) expectErrorOfTypeLength(SimpleSchema.ErrorTypes.EXPECTED_TYPE, schema, { - names: [null], - }); - }); + names: [null] + }) + }) it('null is valid for optional', function () { const schema = new SimpleSchema({ - test: { type: String, optional: true }, - }); + test: { type: String, optional: true } + }) expectValid(schema, { - test: null, - }); - }); + test: null + }) + }) it('issue 360', function () { const schema = new SimpleSchema({ emails: { - type: Array, + type: Array }, 'emails.$': { - type: Object, + type: Object }, 'emails.$.address': { type: String, - regEx: SimpleSchema.RegEx.Email, + regEx: SimpleSchema.RegEx.Email }, 'emails.$.verified': { - type: Boolean, - }, - }); + type: Boolean + } + }) expectErrorOfTypeLength(SimpleSchema.ErrorTypes.EXPECTED_TYPE, schema, { emails: [ { address: 12321, - verified: 'asdasd', - }, - ], - }, { keys: ['emails'] }).to.equal(2); + verified: 'asdasd' + } + ] + }, { keys: ['emails'] }).to.equal(2) expectErrorOfTypeLength(SimpleSchema.ErrorTypes.EXPECTED_TYPE, schema, { emails: [ { address: 12321, - verified: 'asdasd', - }, - ], - }, { keys: ['emails.0'] }).to.equal(2); - }); + verified: 'asdasd' + } + ] + }, { keys: ['emails.0'] }).to.equal(2) + }) it('ignore option', function () { const schema = new SimpleSchema({ - foo: { type: String, optional: true }, - }); + foo: { type: String, optional: true } + }) expectValid(schema, { - foo: 'bar', - }); + foo: 'bar' + }) expectValid(schema, { - foo: 'bar', + foo: 'bar' }, { - ignore: [SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA], - }); + ignore: [SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA] + }) expectValid(schema, { - foo: 'bar', + foo: 'bar' }, { keys: ['foo'], - ignore: [SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA], - }); + ignore: [SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA] + }) expectErrorOfTypeLength(SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA, schema, { - bar: 'foo', - }); + bar: 'foo' + }) expectValid(schema, { - bar: 'foo', + bar: 'foo' }, { - ignore: [SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA], - }); + ignore: [SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA] + }) expectValid(schema, { - bar: 'foo', + bar: 'foo' }, { keys: ['bar'], - ignore: [SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA], - }); - }); + ignore: [SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA] + }) + }) it('ClientError', function () { const schema = new SimpleSchema({ int: SimpleSchema.Integer, - string: String, - }); - - function verify(error) { - expect(error.name).to.equal('ClientError'); - expect(error.errorType).to.equal('ClientError'); - expect(error.error).to.equal('validation-error'); - expect(error.details.length).to.equal(2); - expect(error.details[0].name).to.equal('int'); - expect(error.details[0].type).to.equal(SimpleSchema.ErrorTypes.EXPECTED_TYPE); - expect(error.details[0].message).to.equal('Int must be of type Integer'); - expect(error.details[1].name).to.equal('string'); - expect(error.details[1].type).to.equal(SimpleSchema.ErrorTypes.REQUIRED); - expect(error.details[1].message).to.equal('String is required'); + string: String + }) + + function verify (error) { + expect(error.name).to.equal('ClientError') + expect(error.errorType).to.equal('ClientError') + expect(error.error).to.equal('validation-error') + expect(error.details.length).to.equal(2) + expect(error.details[0].name).to.equal('int') + expect(error.details[0].type).to.equal(SimpleSchema.ErrorTypes.EXPECTED_TYPE) + expect(error.details[0].message).to.equal('Int must be of type Integer') + expect(error.details[1].name).to.equal('string') + expect(error.details[1].type).to.equal(SimpleSchema.ErrorTypes.REQUIRED) + expect(error.details[1].message).to.equal('String is required') // In order for the message at the top of the stack trace to be useful, // we set it to the first validation error message. - expect(error.message).to.equal('Int must be of type Integer'); + expect(error.message).to.equal('Int must be of type Integer') } try { - schema.validate({ int: '5' }); + schema.validate({ int: '5' }) } catch (error) { - verify(error); + verify(error) } try { - SimpleSchema.validate({ int: '5' }, schema); + SimpleSchema.validate({ int: '5' }, schema) } catch (error) { - verify(error); + verify(error) } try { SimpleSchema.validate({ int: '5' }, { int: SimpleSchema.Integer, - string: String, - }); + string: String + }) } catch (error) { - verify(error); + verify(error) } try { - schema.validator()({ int: '5' }); + schema.validator()({ int: '5' }) } catch (error) { - verify(error); + verify(error) } expect(function () { - schema.validator({ clean: true })({ int: '5', string: 'test' }); - }).not.to.throw(); - }); + schema.validator({ clean: true })({ int: '5', string: 'test' }) + }).not.to.throw() + }) it('getFormValidator', function () { const schema = new SimpleSchema({ int: SimpleSchema.Integer, - string: String, - }); + string: String + }) return Promise.all([ schema.getFormValidator()({ int: '5' }).then((errors) => { @@ -639,120 +639,120 @@ describe('SimpleSchema', function () { message: 'Int must be of type Integer', name: 'int', type: 'expectedType', - value: '5', + value: '5' }, { message: 'String is required', name: 'string', type: 'required', - value: undefined, - }, - ]); + value: undefined + } + ]) }), schema.getFormValidator({ clean: true })({ int: '5', string: 'test' }).then((errors) => { - expect(errors).to.deep.equal([]); - }), - ]); - }); + expect(errors).to.deep.equal([]) + }) + ]) + }) it('validate takes an array', function () { const schema = new SimpleSchema({ int: SimpleSchema.Integer, - string: String, - }); - - function verify(error) { - expect(error.name).to.equal('ClientError'); - expect(error.errorType).to.equal('ClientError'); - expect(error.error).to.equal('validation-error'); - expect(error.details.length).to.equal(2); - expect(error.details[0].name).to.equal('int'); - expect(error.details[0].type).to.equal(SimpleSchema.ErrorTypes.EXPECTED_TYPE); - expect(error.details[1].name).to.equal('string'); - expect(error.details[1].type).to.equal(SimpleSchema.ErrorTypes.REQUIRED); + string: String + }) + + function verify (error) { + expect(error.name).to.equal('ClientError') + expect(error.errorType).to.equal('ClientError') + expect(error.error).to.equal('validation-error') + expect(error.details.length).to.equal(2) + expect(error.details[0].name).to.equal('int') + expect(error.details[0].type).to.equal(SimpleSchema.ErrorTypes.EXPECTED_TYPE) + expect(error.details[1].name).to.equal('string') + expect(error.details[1].type).to.equal(SimpleSchema.ErrorTypes.REQUIRED) // In order for the message at the top of the stack trace to be useful, // we set it to the first validation error message. - //expect(error.reason).to.equal('Int must be of type Integer'); - expect(error.message).to.equal('Int must be of type Integer'); + // expect(error.reason).to.equal('Int must be of type Integer'); + expect(error.message).to.equal('Int must be of type Integer') } try { - schema.validate([{ int: 5, string: 'test' }, { int: '5' }]); + schema.validate([{ int: 5, string: 'test' }, { int: '5' }]) } catch (error) { - verify(error); + verify(error) } try { - SimpleSchema.validate([{ int: 5, string: 'test' }, { int: '5' }], schema); + SimpleSchema.validate([{ int: 5, string: 'test' }, { int: '5' }], schema) } catch (error) { - verify(error); + verify(error) } try { SimpleSchema.validate([{ int: 5, string: 'test' }, { int: '5' }], { int: SimpleSchema.Integer, - string: String, - }); + string: String + }) } catch (error) { - verify(error); + verify(error) } try { - schema.validator()([{ int: 5, string: 'test' }, { int: '5' }]); + schema.validator()([{ int: 5, string: 'test' }, { int: '5' }]) } catch (error) { - verify(error); + verify(error) } - }); + }) it('validationErrorTransform', function () { const schema = new SimpleSchema({ - string: String, - }); + string: String + }) SimpleSchema.defineValidationErrorTransform((error) => { - error.message = 'validationErrorTransform'; - return error; - }); + error.message = 'validationErrorTransform' + return error + }) try { - schema.validate({}); + schema.validate({}) } catch (e) { - expect(e.message).to.equal('validationErrorTransform'); + expect(e.message).to.equal('validationErrorTransform') } // Don't mess up other tests - SimpleSchema.validationErrorTransform = null; - }); + SimpleSchema.validationErrorTransform = null + }) it('SimpleSchema.addDocValidator', function () { const schema = new SimpleSchema({ - string: String, - }); + string: String + }) const errorArray = [ - { name: 'firstName', type: 'TOO_SILLY', value: 'Reepicheep' }, - ]; + { name: 'firstName', type: 'TOO_SILLY', value: 'Reepicheep' } + ] const validatedObject = { - string: 'String', - }; + string: 'String' + } SimpleSchema.addDocValidator((obj) => { - expect(obj).to.deep.equal(validatedObject); - return errorArray; - }); + expect(obj).to.deep.equal(validatedObject) + return errorArray + }) - const context = schema.newContext(); - context.validate(validatedObject); + const context = schema.newContext() + context.validate(validatedObject) - expect(context.validationErrors()).to.deep.equal(errorArray); + expect(context.validationErrors()).to.deep.equal(errorArray) // Don't mess up other tests - SimpleSchema._docValidators = []; - }); + SimpleSchema._docValidators = [] + }) it('SimpleSchema.constructorOptionDefaults', function () { - const initialDefaults = SimpleSchema.constructorOptionDefaults(); + const initialDefaults = SimpleSchema.constructorOptionDefaults() // Default defaults expect(initialDefaults).to.deep.equal({ @@ -763,27 +763,27 @@ describe('SimpleSchema', function () { getAutoValues: true, removeEmptyStrings: true, removeNullsFromArrays: false, - trimStrings: true, + trimStrings: true }, humanizeAutoLabels: true, - requiredByDefault: true, - }); + requiredByDefault: true + }) // Verify they are actually used - const schema = new SimpleSchema(); - expect(schema._constructorOptions.humanizeAutoLabels).to.equal(true); - expect(schema._cleanOptions.filter).to.equal(true); + const schema = new SimpleSchema() + expect(schema._constructorOptions.humanizeAutoLabels).to.equal(true) + expect(schema._cleanOptions.filter).to.equal(true) // Change some SimpleSchema.constructorOptionDefaults({ humanizeAutoLabels: false, clean: { - filter: false, - }, - }); + filter: false + } + }) // Verify they are changed - const newDefaults = SimpleSchema.constructorOptionDefaults(); + const newDefaults = SimpleSchema.constructorOptionDefaults() expect(newDefaults).to.deep.equal({ clean: { autoConvert: true, @@ -792,43 +792,43 @@ describe('SimpleSchema', function () { getAutoValues: true, removeEmptyStrings: true, removeNullsFromArrays: false, - trimStrings: true, + trimStrings: true }, humanizeAutoLabels: false, - requiredByDefault: true, - }); + requiredByDefault: true + }) // Verify they are actually used - const otherSchema = new SimpleSchema(); - expect(otherSchema._constructorOptions.humanizeAutoLabels).to.equal(false); - expect(otherSchema._cleanOptions.filter).to.equal(false); + const otherSchema = new SimpleSchema() + expect(otherSchema._constructorOptions.humanizeAutoLabels).to.equal(false) + expect(otherSchema._cleanOptions.filter).to.equal(false) // Don't mess up other tests - SimpleSchema.constructorOptionDefaults(initialDefaults); - }); + SimpleSchema.constructorOptionDefaults(initialDefaults) + }) it('addDocValidator', function () { const schema = new SimpleSchema({ - string: String, - }); + string: String + }) const errorArray = [ - { name: 'firstName', type: 'TOO_SILLY', value: 'Reepicheep' }, - ]; + { name: 'firstName', type: 'TOO_SILLY', value: 'Reepicheep' } + ] const validatedObject = { - string: 'String', - }; + string: 'String' + } schema.addDocValidator((obj) => { - expect(obj).to.deep.equal(validatedObject); - return errorArray; - }); + expect(obj).to.deep.equal(validatedObject) + return errorArray + }) - const context = schema.newContext(); - context.validate(validatedObject); + const context = schema.newContext() + context.validate(validatedObject) - expect(context.validationErrors()).to.deep.equal(errorArray); - }); + expect(context.validationErrors()).to.deep.equal(errorArray) + }) describe('objectKeys', function () { it('gets objectKeys', function () { @@ -838,16 +838,16 @@ describe('SimpleSchema', function () { 'a.b.c': Array, 'a.b.c.$': Object, 'a.b.c.$.d': Object, - 'a.b.c.$.d.e': String, - }); + 'a.b.c.$.d.e': String + }) - expect(schema.objectKeys()).to.deep.equal(['a']); - expect(schema.objectKeys('a')).to.deep.equal(['b']); - expect(schema.objectKeys('a.b')).to.deep.equal(['c']); - expect(schema.objectKeys('a.b.c')).to.deep.equal([]); - expect(schema.objectKeys('a.b.c.$')).to.deep.equal(['d']); - expect(schema.objectKeys('a.b.c.$.d')).to.deep.equal(['e']); - }); + expect(schema.objectKeys()).to.deep.equal(['a']) + expect(schema.objectKeys('a')).to.deep.equal(['b']) + expect(schema.objectKeys('a.b')).to.deep.equal(['c']) + expect(schema.objectKeys('a.b.c')).to.deep.equal([]) + expect(schema.objectKeys('a.b.c.$')).to.deep.equal(['d']) + expect(schema.objectKeys('a.b.c.$.d')).to.deep.equal(['e']) + }) it('gets subschema objectKeys', function () { const schema = new SimpleSchema({ @@ -856,18 +856,18 @@ describe('SimpleSchema', function () { b: { type: new SimpleSchema({ c: { - type: String, - }, - }), - }, - }), - }, - }); - - expect(schema.objectKeys('a')).to.deep.equal(['b']); - expect(schema.objectKeys('a.b')).to.deep.equal(['c']); - }); - }); + type: String + } + }) + } + }) + } + }) + + expect(schema.objectKeys('a')).to.deep.equal(['b']) + expect(schema.objectKeys('a.b')).to.deep.equal(['c']) + }) + }) it('gets schema property by key', function () { const schema = new SimpleSchema({ @@ -877,28 +877,28 @@ describe('SimpleSchema', function () { type: new SimpleSchema({ c: { type: String, - defaultValue: 'abc', - }, + defaultValue: 'abc' + } }), - defaultValue: 'ab', + defaultValue: 'ab' }, d: SimpleSchema.oneOf({ type: Array, minCount: 0, - maxCount: 3, + maxCount: 3 }, { type: SimpleSchema.Integer, - min: 0, + min: 0 }), - 'd.$': String, - }), - }, - }); + 'd.$': String + }) + } + }) - expect(schema.get('a', 'defaultValue')).to.equal(undefined); - expect(schema.get('a.b', 'defaultValue')).to.equal('ab'); - expect(schema.get('a.d', 'maxCount')).to.equal(3); - }); + expect(schema.get('a', 'defaultValue')).to.equal(undefined) + expect(schema.get('a.b', 'defaultValue')).to.equal('ab') + expect(schema.get('a.d', 'maxCount')).to.equal(3) + }) it('exposes defaultValue for a key', function () { const schema = new SimpleSchema({ @@ -908,97 +908,97 @@ describe('SimpleSchema', function () { type: new SimpleSchema({ c: { type: String, - defaultValue: 'abc', - }, + defaultValue: 'abc' + } }), - defaultValue: 'ab', - }, - }), - }, - }); + defaultValue: 'ab' + } + }) + } + }) - expect(schema.defaultValue('a')).to.equal(undefined); - expect(schema.defaultValue('a.b')).to.equal('ab'); - expect(schema.defaultValue('a.b.c')).to.equal('abc'); - }); + expect(schema.defaultValue('a')).to.equal(undefined) + expect(schema.defaultValue('a.b')).to.equal('ab') + expect(schema.defaultValue('a.b.c')).to.equal('abc') + }) it('issue #232', function () { - let foo; + let foo expect(function () { const schema3 = new SimpleSchema({ - foo: String, - }); + foo: String + }) const schema2 = new SimpleSchema({ field2: { type: Array, - optional: true, + optional: true }, - 'field2.$': schema3, - }); + 'field2.$': schema3 + }) foo = new SimpleSchema({ field1: { type: schema2, - defaultValue: {}, - }, - }); - }).not.to.throw(); + defaultValue: {} + } + }) + }).not.to.throw() - expect(foo instanceof SimpleSchema).to.equal(true); - }); + expect(foo instanceof SimpleSchema).to.equal(true) + }) it('issue #390 - Should get null rawDefinition if keepRawDefiniton is false', function () { const foo = new SimpleSchema({ - foo: String, - }); - expect(foo instanceof SimpleSchema).to.equal(true); - expect(foo.rawDefinition).to.deep.equal(null); - }); + foo: String + }) + expect(foo instanceof SimpleSchema).to.equal(true) + expect(foo.rawDefinition).to.deep.equal(null) + }) it('issue #390 - Should get rawDefinition if keepRawDefiniton is true', function () { const foo = new SimpleSchema({ - foo: String, - }, { keepRawDefinition: true }); - expect(foo instanceof SimpleSchema).to.equal(true); - expect(foo.rawDefinition).to.deep.equal({ foo: String }); - }); + foo: String + }, { keepRawDefinition: true }) + expect(foo instanceof SimpleSchema).to.equal(true) + expect(foo.rawDefinition).to.deep.equal({ foo: String }) + }) it('$currentDate Date validation', function () { const schema = new SimpleSchema({ - date: Date, - }); - const context = schema.namedContext(); + date: Date + }) + const context = schema.namedContext() let testModifer = { $currentDate: { - date: true, - }, - }; - expect(context.validate(testModifer, { modifier: true })).to.equal(true); + date: true + } + } + expect(context.validate(testModifer, { modifier: true })).to.equal(true) testModifer = { $currentDate: { - date: { $type: 'date' }, - }, - }; - context.validate(testModifer, { modifier: true }); - expect(context.validate(testModifer, { modifier: true })).to.equal(true); + date: { $type: 'date' } + } + } + context.validate(testModifer, { modifier: true }) + expect(context.validate(testModifer, { modifier: true })).to.equal(true) // timestamp fails because it would save a MongoDB.Timestamp value into a Date field testModifer = { $currentDate: { - date: { $type: 'timestamp' }, - }, - }; - expect(context.validate(testModifer, { modifier: true })).to.equal(false); - }); + date: { $type: 'timestamp' } + } + } + expect(context.validate(testModifer, { modifier: true })).to.equal(false) + }) describe('SimpleSchema.Any', function () { const schema = new SimpleSchema({ - testAny: SimpleSchema.Any, - }); + testAny: SimpleSchema.Any + }) describe('can be used to allow a key with type', function () { const dataTypes = [ ["String 'string'", 'string'], @@ -1011,26 +1011,26 @@ describe('SimpleSchema', function () { ['Number NaN', NaN], ['Date new Date()', new Date()], ['Boolean true', true], - ['Boolean false', false], - ]; + ['Boolean false', false] + ] dataTypes.forEach(([label, type]) => { describe(label, function () { it("on it's own", function () { - expectValid(schema, { testAny: type }); - }); + expectValid(schema, { testAny: type }) + }) it('as a nested key', function () { expectValid( new SimpleSchema({ testNested: schema }), - { testNested: { testAny: { test: type } } }, - ); - }); - }); - }); - }); - - describe('with modifiers', function() { + { testNested: { testAny: { test: type } } } + ) + }) + }) + }) + }) + + describe('with modifiers', function () { const shouldBeValidModifiers = [ '$set', '$setOnInsert', @@ -1041,99 +1041,99 @@ describe('SimpleSchema', function () { '$mul', '$pop', '$pull', - '$pullAll', - ]; + '$pullAll' + ] shouldBeValidModifiers.forEach((mod) => { describe(mod, function () { - it(`can be used for ${mod} modifiers`, function() { + it(`can be used for ${mod} modifiers`, function () { expectValid( schema, { [mod]: { testAny: 3.1415 } }, - { modifier: true }, - ); - }); - it(`can be used for nested ${mod} modifiers`, function() { - const parentSchema = new SimpleSchema({ parent: schema }); + { modifier: true } + ) + }) + it(`can be used for nested ${mod} modifiers`, function () { + const parentSchema = new SimpleSchema({ parent: schema }) expectValid( parentSchema, { [mod]: { parent: { testAny: 3.1415 } } }, - { modifier: true }, - ); - }); - it(`can be used for nested ${mod} modifiers with dot notation`, function() { - const parentSchema = new SimpleSchema({ parent: schema }); + { modifier: true } + ) + }) + it(`can be used for nested ${mod} modifiers with dot notation`, function () { + const parentSchema = new SimpleSchema({ parent: schema }) expectValid( parentSchema, { [mod]: { 'parent.testAny': 3.1415 } }, - { modifier: true }, - ); - }); - }); - }); + { modifier: true } + ) + }) + }) + }) // Special cases where we don't expect it to work like the rest: describe('$unset', function () { - it('can be used for $unset modifiers', function() { + it('can be used for $unset modifiers', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.REQUIRED, schema, { $unset: { testAny: 1 } }, - { modifier: true }, - ).to.deep.equal(1); - }); - it('can be used for nested $unset modifiers', function() { - const parentSchema = new SimpleSchema({ parent: schema }); + { modifier: true } + ).to.deep.equal(1) + }) + it('can be used for nested $unset modifiers', function () { + const parentSchema = new SimpleSchema({ parent: schema }) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.REQUIRED, parentSchema, { $unset: { parent: 1 } }, - { modifier: true }, - ).to.deep.equal(1); - }); - it('can be used for nested $unset modifiers with dot notation', function() { - const parentSchema = new SimpleSchema({ parent: schema }); + { modifier: true } + ).to.deep.equal(1) + }) + it('can be used for nested $unset modifiers with dot notation', function () { + const parentSchema = new SimpleSchema({ parent: schema }) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.REQUIRED, parentSchema, { $unset: { 'parent.testAny': 1 } }, - { modifier: true }, - ).to.deep.equal(1); - }); - }); + { modifier: true } + ).to.deep.equal(1) + }) + }) describe('$addToSet', function () { - it('can be used for $addToSet modifiers', function() { + it('can be used for $addToSet modifiers', function () { expectValid( schema, { $addToSet: { testAny: 1 } }, - { modifier: true }, - ); - }); - it('can be used for nested $addToSet modifiers with dot notation', function() { - const parentSchema = new SimpleSchema({ parent: schema }); + { modifier: true } + ) + }) + it('can be used for nested $addToSet modifiers with dot notation', function () { + const parentSchema = new SimpleSchema({ parent: schema }) expectValid( parentSchema, { $addToSet: { 'parent.testAny': 3.1415 } }, - { modifier: true }, - ); - }); - }); + { modifier: true } + ) + }) + }) describe('$push', function () { - it('can be used for $push modifiers', function() { + it('can be used for $push modifiers', function () { expectValid( schema, { $push: { testAny: 1 } }, - { modifier: true }, - ); - }); - it('can be used for nested $push modifiers with dot notation', function() { - const parentSchema = new SimpleSchema({ parent: schema }); + { modifier: true } + ) + }) + it('can be used for nested $push modifiers with dot notation', function () { + const parentSchema = new SimpleSchema({ parent: schema }) expectValid( parentSchema, { $push: { 'parent.testAny': 3.1415 } }, - { modifier: true }, - ); - }); - }); - }); - }); -}); + { modifier: true } + ) + }) + }) + }) + }) +}) diff --git a/lib/SimpleSchemaGroup.js b/lib/SimpleSchemaGroup.js index 52f1f99..dbf1145 100644 --- a/lib/SimpleSchemaGroup.js +++ b/lib/SimpleSchemaGroup.js @@ -1,39 +1,39 @@ -import MongoObject from 'mongo-object'; +import MongoObject from 'mongo-object' class SimpleSchemaGroup { - constructor(...definitions) { + constructor (...definitions) { this.definitions = definitions.map((definition) => { if (MongoObject.isBasicObject(definition)) { - return { ...definition }; + return { ...definition } } if (definition instanceof RegExp) { return { type: String, - regEx: definition, - }; + regEx: definition + } } - return { type: definition }; - }); + return { type: definition } + }) } - get singleType() { - return this.definitions[0].type; + get singleType () { + return this.definitions[0].type } - clone() { - return new SimpleSchemaGroup(...this.definitions); + clone () { + return new SimpleSchemaGroup(...this.definitions) } - extend(otherGroup) { + extend (otherGroup) { // We extend based on index being the same. No better way I can think of at the moment. this.definitions = this.definitions.map((def, index) => { - const otherDef = otherGroup.definitions[index]; - if (!otherDef) return def; - return { ...def, ...otherDef }; - }); + const otherDef = otherGroup.definitions[index] + if (!otherDef) return def + return { ...def, ...otherDef } + }) } } -export default SimpleSchemaGroup; +export default SimpleSchemaGroup diff --git a/lib/SimpleSchema_allowedValues.tests.js b/lib/SimpleSchema_allowedValues.tests.js index ef69387..ec06fa8 100644 --- a/lib/SimpleSchema_allowedValues.tests.js +++ b/lib/SimpleSchema_allowedValues.tests.js @@ -1,73 +1,73 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; -import friendsSchema from './testHelpers/friendsSchema'; -import testSchema from './testHelpers/testSchema'; -import expectErrorLength from './testHelpers/expectErrorLength'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' +import friendsSchema from './testHelpers/friendsSchema' +import testSchema from './testHelpers/testSchema' +import expectErrorLength from './testHelpers/expectErrorLength' describe('SimpleSchema - allowedValues', function () { describe('normal', function () { it('valid string', function () { expectErrorLength(testSchema, { - allowedStrings: 'tuna', - }).to.deep.equal(0); + allowedStrings: 'tuna' + }).to.deep.equal(0) expectErrorLength(testSchema, { - allowedStringsArray: ['tuna', 'fish', 'salad'], - }).to.deep.equal(0); + allowedStringsArray: ['tuna', 'fish', 'salad'] + }).to.deep.equal(0) expectErrorLength(testSchema, { - allowedStringsSet: ['tuna', 'fish', 'salad'], - }).to.deep.equal(0); + allowedStringsSet: ['tuna', 'fish', 'salad'] + }).to.deep.equal(0) // Array of objects expectErrorLength(friendsSchema, { friends: [{ name: 'Bob', - type: 'best', + type: 'best' }], - enemies: [], - }).to.deep.equal(0); - }); + enemies: [] + }).to.deep.equal(0) + }) it('invalid string', function () { expectErrorLength(testSchema, { - allowedStrings: 'tunas', - }).to.deep.equal(1); + allowedStrings: 'tunas' + }).to.deep.equal(1) // Array expectErrorLength(testSchema, { - allowedStringsArray: ['tuna', 'fish', 'sandwich'], - }).to.deep.equal(1); + allowedStringsArray: ['tuna', 'fish', 'sandwich'] + }).to.deep.equal(1) // Set Or Array expectErrorLength(testSchema, { - allowedStringsSet: ['tuna', 'fish', 'sandwich'], - }).to.deep.equal(1); + allowedStringsSet: ['tuna', 'fish', 'sandwich'] + }).to.deep.equal(1) // Array of objects expectErrorLength(friendsSchema, { friends: [{ name: 'Bob', - type: 'smelly', + type: 'smelly' }], - enemies: [], - }).to.deep.equal(1); - }); + enemies: [] + }).to.deep.equal(1) + }) it('valid number', function () { expectErrorLength(testSchema, { - allowedNumbers: 1, - }).to.deep.equal(0); + allowedNumbers: 1 + }).to.deep.equal(0) expectErrorLength(testSchema, { - allowedNumbersArray: [1, 2, 3], - }).to.deep.equal(0); + allowedNumbersArray: [1, 2, 3] + }).to.deep.equal(0) expectErrorLength(testSchema, { - allowedNumbersSet: [1, 2, 3], - }).to.deep.equal(0); + allowedNumbersSet: [1, 2, 3] + }).to.deep.equal(0) // Array of objects expectErrorLength(friendsSchema, { @@ -75,27 +75,27 @@ describe('SimpleSchema - allowedValues', function () { name: 'Bob', type: 'best', a: { - b: 5000, - }, + b: 5000 + } }], - enemies: [], - }).to.deep.equal(0); - }); + enemies: [] + }).to.deep.equal(0) + }) it('invalid number', function () { expectErrorLength(testSchema, { - allowedNumbers: 4, - }).to.deep.equal(1); + allowedNumbers: 4 + }).to.deep.equal(1) // Array expectErrorLength(testSchema, { - allowedNumbersArray: [1, 2, 3, 4], - }).to.deep.equal(1); + allowedNumbersArray: [1, 2, 3, 4] + }).to.deep.equal(1) // Set or Array expectErrorLength(testSchema, { - allowedNumbersSet: [1, 2, 3, 4], - }).to.deep.equal(1); + allowedNumbersSet: [1, 2, 3, 4] + }).to.deep.equal(1) // Array of objects expectErrorLength(friendsSchema, { @@ -103,101 +103,101 @@ describe('SimpleSchema - allowedValues', function () { name: 'Bob', type: 'best', a: { - b: 'wrong', - }, + b: 'wrong' + } }], - enemies: [], - }).to.deep.equal(1); - }); - }); + enemies: [] + }).to.deep.equal(1) + }) + }) describe('modifier with $setOnInsert', function () { it('valid string', function () { expectErrorLength(testSchema, { $setOnInsert: { - allowedStrings: 'tuna', - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + allowedStrings: 'tuna' + } + }, { modifier: true, upsert: true }).to.deep.equal(0) // Array expectErrorLength(testSchema, { $setOnInsert: { - allowedStringsArray: ['tuna', 'fish', 'salad'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + allowedStringsArray: ['tuna', 'fish', 'salad'] + } + }, { modifier: true, upsert: true }).to.deep.equal(0) // Set or Array expectErrorLength(testSchema, { $setOnInsert: { - allowedStringsSet: ['tuna', 'fish', 'salad'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + allowedStringsSet: ['tuna', 'fish', 'salad'] + } + }, { modifier: true, upsert: true }).to.deep.equal(0) // Array of objects expectErrorLength(friendsSchema, { $setOnInsert: { friends: [{ name: 'Bob', - type: 'best', + type: 'best' }], - enemies: [], - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); - }); + enemies: [] + } + }, { modifier: true, upsert: true }).to.deep.equal(0) + }) it('invalid string', function () { expectErrorLength(testSchema, { $setOnInsert: { - allowedStrings: 'tunas', - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + allowedStrings: 'tunas' + } + }, { modifier: true, upsert: true }).to.deep.equal(1) // Array expectErrorLength(testSchema, { $setOnInsert: { - allowedStringsArray: ['tuna', 'fish', 'sandwich'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + allowedStringsArray: ['tuna', 'fish', 'sandwich'] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) // Set or Array expectErrorLength(testSchema, { $setOnInsert: { - allowedStringsSet: ['tuna', 'fish', 'sandwich'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + allowedStringsSet: ['tuna', 'fish', 'sandwich'] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) // Array of objects expectErrorLength(friendsSchema, { $setOnInsert: { friends: [{ name: 'Bob', - type: 'smelly', + type: 'smelly' }], - enemies: [], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); + enemies: [] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) it('valid number', function () { expectErrorLength(testSchema, { $setOnInsert: { - allowedNumbers: 1, - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + allowedNumbers: 1 + } + }, { modifier: true, upsert: true }).to.deep.equal(0) // Array expectErrorLength(testSchema, { $setOnInsert: { - allowedNumbersArray: [1, 2, 3], - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + allowedNumbersArray: [1, 2, 3] + } + }, { modifier: true, upsert: true }).to.deep.equal(0) // Set or Array expectErrorLength(testSchema, { $setOnInsert: { - allowedNumbersSet: [1, 2, 3], - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + allowedNumbersSet: [1, 2, 3] + } + }, { modifier: true, upsert: true }).to.deep.equal(0) // Array of objects expectErrorLength(friendsSchema, { @@ -206,34 +206,34 @@ describe('SimpleSchema - allowedValues', function () { name: 'Bob', type: 'best', a: { - b: 5000, - }, + b: 5000 + } }], - enemies: [], - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); - }); + enemies: [] + } + }, { modifier: true, upsert: true }).to.deep.equal(0) + }) it('invalid number', function () { expectErrorLength(testSchema, { $setOnInsert: { - allowedNumbers: 4, - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + allowedNumbers: 4 + } + }, { modifier: true, upsert: true }).to.deep.equal(1) // Array expectErrorLength(testSchema, { $setOnInsert: { - allowedNumbersArray: [1, 2, 3, 4], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + allowedNumbersArray: [1, 2, 3, 4] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) // Set or Array expectErrorLength(testSchema, { $setOnInsert: { - allowedNumbersSet: [1, 2, 3, 4], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + allowedNumbersSet: [1, 2, 3, 4] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) // Array of objects expectErrorLength(friendsSchema, { @@ -242,163 +242,163 @@ describe('SimpleSchema - allowedValues', function () { name: 'Bob', type: 'best', a: { - b: 'wrong', - }, + b: 'wrong' + } }], - enemies: [], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); - }); + enemies: [] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) + }) describe('modifier with $set', function () { it('valid string', function () { expectErrorLength(testSchema, { $set: { - allowedStrings: 'tuna', - }, - }, { modifier: true }).to.deep.equal(0); + allowedStrings: 'tuna' + } + }, { modifier: true }).to.deep.equal(0) // Array expectErrorLength(testSchema, { $set: { - allowedStringsArray: ['tuna', 'fish', 'salad'], - }, - }, { modifier: true }).to.deep.equal(0); + allowedStringsArray: ['tuna', 'fish', 'salad'] + } + }, { modifier: true }).to.deep.equal(0) // Set or Array expectErrorLength(testSchema, { $set: { - allowedStringsSet: ['tuna', 'fish', 'salad'], - }, - }, { modifier: true }).to.deep.equal(0); + allowedStringsSet: ['tuna', 'fish', 'salad'] + } + }, { modifier: true }).to.deep.equal(0) // Array of objects expectErrorLength(friendsSchema, { $set: { - 'friends.$.name': 'Bob', - }, - }, { modifier: true }).to.deep.equal(0); + 'friends.$.name': 'Bob' + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(friendsSchema, { $set: { - 'friends.1.name': 'Bob', - }, - }, { modifier: true }).to.deep.equal(0); - }); + 'friends.1.name': 'Bob' + } + }, { modifier: true }).to.deep.equal(0) + }) it('invalid string', function () { expectErrorLength(testSchema, { $set: { - allowedStrings: 'tunas', - }, - }, { modifier: true }).to.deep.equal(1); + allowedStrings: 'tunas' + } + }, { modifier: true }).to.deep.equal(1) // Array expectErrorLength(testSchema, { $set: { - allowedStringsArray: ['tuna', 'fish', 'sandwich'], - }, - }, { modifier: true }).to.deep.equal(1); + allowedStringsArray: ['tuna', 'fish', 'sandwich'] + } + }, { modifier: true }).to.deep.equal(1) // Set or Array expectErrorLength(testSchema, { $set: { - allowedStringsSet: ['tuna', 'fish', 'sandwich'], - }, - }, { modifier: true }).to.deep.equal(1); + allowedStringsSet: ['tuna', 'fish', 'sandwich'] + } + }, { modifier: true }).to.deep.equal(1) // Array of objects expectErrorLength(friendsSchema, { $set: { - 'friends.$.name': 'Bobby', - }, - }, { modifier: true }).to.deep.equal(1); + 'friends.$.name': 'Bobby' + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(friendsSchema, { $set: { - 'friends.1.name': 'Bobby', - }, - }, { modifier: true }).to.deep.equal(1); - }); + 'friends.1.name': 'Bobby' + } + }, { modifier: true }).to.deep.equal(1) + }) it('valid number', function () { expectErrorLength(testSchema, { $set: { - allowedNumbers: 1, - }, - }, { modifier: true }).to.deep.equal(0); + allowedNumbers: 1 + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - allowedNumbersArray: [1, 2, 3], - }, - }, { modifier: true }).to.deep.equal(0); + allowedNumbersArray: [1, 2, 3] + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - allowedNumbersSet: [1, 2, 3], - }, - }, { modifier: true }).to.deep.equal(0); - }); + allowedNumbersSet: [1, 2, 3] + } + }, { modifier: true }).to.deep.equal(0) + }) it('invalid number', function () { expectErrorLength(testSchema, { $set: { - allowedNumbers: 4, - }, - }, { modifier: true }).to.deep.equal(1); + allowedNumbers: 4 + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - allowedNumbersArray: [1, 2, 3, 4], - }, - }, { modifier: true }).to.deep.equal(1); + allowedNumbersArray: [1, 2, 3, 4] + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - allowedNumbersSet: [1, 2, 3, 4], - }, - }, { modifier: true }).to.deep.equal(1); - }); - }); + allowedNumbersSet: [1, 2, 3, 4] + } + }, { modifier: true }).to.deep.equal(1) + }) + }) describe('getAllowedValuesForKey', function () { it('works', function () { - const allowedValues = ['a', 'b']; + const allowedValues = ['a', 'b'] const schema = new SimpleSchema({ foo: Array, 'foo.$': { type: String, - allowedValues, - }, - }); - expect(schema.getAllowedValuesForKey('foo')).to.deep.equal(allowedValues); - }); + allowedValues + } + }) + expect(schema.getAllowedValuesForKey('foo')).to.deep.equal(allowedValues) + }) it('works with set, convert to array', function () { - const allowedValues = new Set(['a', 'b']); + const allowedValues = new Set(['a', 'b']) const schema = new SimpleSchema({ foo: Array, 'foo.$': { type: String, - allowedValues, - }, - }); - const fetchedAllowedValues = schema.getAllowedValuesForKey('foo'); - expect(fetchedAllowedValues.includes('a')).to.be.ok; - expect(fetchedAllowedValues.includes('b')).to.be.ok; - expect(fetchedAllowedValues.length).to.deep.equal(2); - }); + allowedValues + } + }) + const fetchedAllowedValues = schema.getAllowedValuesForKey('foo') + expect(fetchedAllowedValues.includes('a')).to.equal(true) + expect(fetchedAllowedValues.includes('b')).to.equal(true) + expect(fetchedAllowedValues.length).to.deep.equal(2) + }) it('returns null when allowedValues key is empty', function () { const schema = new SimpleSchema({ foo: Array, 'foo.$': { - type: String, - }, - }); - expect(schema.getAllowedValuesForKey('foo')).to.deep.equal(null); - }); - }); -}); + type: String + } + }) + expect(schema.getAllowedValuesForKey('foo')).to.deep.equal(null) + }) + }) +}) diff --git a/lib/SimpleSchema_autoValueFunctions.tests.js b/lib/SimpleSchema_autoValueFunctions.tests.js index 6c1096f..ac2e9e0 100644 --- a/lib/SimpleSchema_autoValueFunctions.tests.js +++ b/lib/SimpleSchema_autoValueFunctions.tests.js @@ -1,170 +1,170 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema - autoValueFunctions', function () { it('simple', function () { const schema = new SimpleSchema({ a: { type: String, - autoValue() {}, - }, - }); + autoValue () {} + } + }) - const autoValueFunctions = schema.autoValueFunctions(); - expect(autoValueFunctions.length).to.equal(1); - expect(!!autoValueFunctions[0].func).to.equal(true); - expect(autoValueFunctions[0].fieldName).to.equal('a'); - expect(autoValueFunctions[0].closestSubschemaFieldName).to.equal(''); - }); + const autoValueFunctions = schema.autoValueFunctions() + expect(autoValueFunctions.length).to.equal(1) + expect(!!autoValueFunctions[0].func).to.equal(true) + expect(autoValueFunctions[0].fieldName).to.equal('a') + expect(autoValueFunctions[0].closestSubschemaFieldName).to.equal('') + }) it('one level of subschema', function () { const subschema = new SimpleSchema({ z: { type: Object, - autoValue() {}, - }, - }); + autoValue () {} + } + }) const schema = new SimpleSchema({ a: { type: Object, - autoValue() {}, + autoValue () {} }, 'a.b': { type: String, - autoValue() {}, + autoValue () {} }, c: { - type: subschema, - }, - }); + type: subschema + } + }) - const autoValueFunctions = schema.autoValueFunctions(); - expect(autoValueFunctions.length).to.equal(3); + const autoValueFunctions = schema.autoValueFunctions() + expect(autoValueFunctions.length).to.equal(3) - expect(!!autoValueFunctions[0].func).to.equal(true); - expect(autoValueFunctions[0].fieldName).to.equal('a'); - expect(autoValueFunctions[0].closestSubschemaFieldName).to.equal(''); + expect(!!autoValueFunctions[0].func).to.equal(true) + expect(autoValueFunctions[0].fieldName).to.equal('a') + expect(autoValueFunctions[0].closestSubschemaFieldName).to.equal('') - expect(!!autoValueFunctions[1].func).to.equal(true); - expect(autoValueFunctions[1].fieldName).to.equal('a.b'); - expect(autoValueFunctions[1].closestSubschemaFieldName).to.equal(''); + expect(!!autoValueFunctions[1].func).to.equal(true) + expect(autoValueFunctions[1].fieldName).to.equal('a.b') + expect(autoValueFunctions[1].closestSubschemaFieldName).to.equal('') - expect(!!autoValueFunctions[2].func).to.equal(true); - expect(autoValueFunctions[2].fieldName).to.equal('c.z'); - expect(autoValueFunctions[2].closestSubschemaFieldName).to.equal('c'); - }); + expect(!!autoValueFunctions[2].func).to.equal(true) + expect(autoValueFunctions[2].fieldName).to.equal('c.z') + expect(autoValueFunctions[2].closestSubschemaFieldName).to.equal('c') + }) it('two levels of subschemas', function () { const subschema1 = new SimpleSchema({ x: { type: Object, - autoValue() {}, + autoValue () {} }, 'x.m': { type: Array, - autoValue() {}, + autoValue () {} }, 'x.m.$': { - type: String, - }, - }); + type: String + } + }) const subschema2 = new SimpleSchema({ z: { type: Object, - autoValue() {}, + autoValue () {} }, 'z.y': { - type: subschema1, - }, - }); + type: subschema1 + } + }) const schema = new SimpleSchema({ a: { type: Object, - autoValue() {}, + autoValue () {} }, 'a.b': { type: String, - autoValue() {}, + autoValue () {} }, c: { - type: subschema2, - }, - }); + type: subschema2 + } + }) - const autoValueFunctions = schema.autoValueFunctions(); - expect(autoValueFunctions.length).to.equal(5); + const autoValueFunctions = schema.autoValueFunctions() + expect(autoValueFunctions.length).to.equal(5) - expect(!!autoValueFunctions[0].func).to.equal(true); - expect(autoValueFunctions[0].fieldName).to.equal('a'); - expect(autoValueFunctions[0].closestSubschemaFieldName).to.equal(''); + expect(!!autoValueFunctions[0].func).to.equal(true) + expect(autoValueFunctions[0].fieldName).to.equal('a') + expect(autoValueFunctions[0].closestSubschemaFieldName).to.equal('') - expect(!!autoValueFunctions[1].func).to.equal(true); - expect(autoValueFunctions[1].fieldName).to.equal('a.b'); - expect(autoValueFunctions[1].closestSubschemaFieldName).to.equal(''); + expect(!!autoValueFunctions[1].func).to.equal(true) + expect(autoValueFunctions[1].fieldName).to.equal('a.b') + expect(autoValueFunctions[1].closestSubschemaFieldName).to.equal('') - expect(!!autoValueFunctions[2].func).to.equal(true); - expect(autoValueFunctions[2].fieldName).to.equal('c.z'); - expect(autoValueFunctions[2].closestSubschemaFieldName).to.equal('c'); + expect(!!autoValueFunctions[2].func).to.equal(true) + expect(autoValueFunctions[2].fieldName).to.equal('c.z') + expect(autoValueFunctions[2].closestSubschemaFieldName).to.equal('c') - expect(!!autoValueFunctions[3].func).to.equal(true); - expect(autoValueFunctions[3].fieldName).to.equal('c.z.y.x'); - expect(autoValueFunctions[3].closestSubschemaFieldName).to.equal('c.z.y'); + expect(!!autoValueFunctions[3].func).to.equal(true) + expect(autoValueFunctions[3].fieldName).to.equal('c.z.y.x') + expect(autoValueFunctions[3].closestSubschemaFieldName).to.equal('c.z.y') - expect(!!autoValueFunctions[4].func).to.equal(true); - expect(autoValueFunctions[4].fieldName).to.equal('c.z.y.x.m'); - expect(autoValueFunctions[4].closestSubschemaFieldName).to.equal('c.z.y'); - }); + expect(!!autoValueFunctions[4].func).to.equal(true) + expect(autoValueFunctions[4].fieldName).to.equal('c.z.y.x.m') + expect(autoValueFunctions[4].closestSubschemaFieldName).to.equal('c.z.y') + }) it('array of objects', function () { const subschema = new SimpleSchema({ z: { type: String, - autoValue() {}, - }, - }); + autoValue () {} + } + }) const schema = new SimpleSchema({ a: { type: Object, - autoValue() {}, + autoValue () {} }, 'a.b': { - type: Array, + type: Array }, 'a.b.$': { - type: subschema, - }, - }); + type: subschema + } + }) - const autoValueFunctions = schema.autoValueFunctions(); - expect(autoValueFunctions.length).to.equal(2); + const autoValueFunctions = schema.autoValueFunctions() + expect(autoValueFunctions.length).to.equal(2) - expect(!!autoValueFunctions[0].func).to.equal(true); - expect(autoValueFunctions[0].fieldName).to.equal('a'); - expect(autoValueFunctions[0].closestSubschemaFieldName).to.equal(''); + expect(!!autoValueFunctions[0].func).to.equal(true) + expect(autoValueFunctions[0].fieldName).to.equal('a') + expect(autoValueFunctions[0].closestSubschemaFieldName).to.equal('') - expect(!!autoValueFunctions[1].func).to.equal(true); - expect(autoValueFunctions[1].fieldName).to.equal('a.b.$.z'); - expect(autoValueFunctions[1].closestSubschemaFieldName).to.equal('a.b.$'); - }); + expect(!!autoValueFunctions[1].func).to.equal(true) + expect(autoValueFunctions[1].fieldName).to.equal('a.b.$.z') + expect(autoValueFunctions[1].closestSubschemaFieldName).to.equal('a.b.$') + }) it('async functions', async function () { const schema = new SimpleSchema({ a: { type: String, - autoValue() { + autoValue () { return new Promise((resolve) => { - resolve('a'); - }); - }, - }, - }); - const b = await schema.clean({}); - expect(b).to.deep.equal({ a: 'a' }); - }); -}); + resolve('a') + }) + } + } + }) + const b = await schema.clean({}) + expect(b).to.deep.equal({ a: 'a' }) + }) +}) diff --git a/lib/SimpleSchema_blackbox.tests.js b/lib/SimpleSchema_blackbox.tests.js index 9daadac..a0e1cab 100644 --- a/lib/SimpleSchema_blackbox.tests.js +++ b/lib/SimpleSchema_blackbox.tests.js @@ -1,60 +1,60 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import expectErrorLength from './testHelpers/expectErrorLength'; -import { SimpleSchema } from './SimpleSchema'; +import expectErrorLength from './testHelpers/expectErrorLength' +import { SimpleSchema } from './SimpleSchema' const schema = new SimpleSchema({ blackBoxObject: { type: Object, optional: true, - blackbox: true, - }, -}); + blackbox: true + } +}) describe('SimpleSchema - blackbox', function () { it('allows an empty object', function () { expectErrorLength(schema, { - blackBoxObject: {}, - }).to.deep.equal(0); - }); + blackBoxObject: {} + }).to.deep.equal(0) + }) it('allows any properties', function () { expectErrorLength(schema, { blackBoxObject: { - foo: 'bar', - }, - }).to.deep.equal(0); - }); + foo: 'bar' + } + }).to.deep.equal(0) + }) it('allows any properties on $set object', function () { expectErrorLength(schema, { $set: { blackBoxObject: { - foo: 'bar', - }, - }, - }, { modifier: true }).to.deep.equal(0); - }); + foo: 'bar' + } + } + }, { modifier: true }).to.deep.equal(0) + }) it('allows to $set any subobject', function () { expectErrorLength(schema, { $set: { - 'blackBoxObject.foo': 'bar', - }, - }, { modifier: true }).to.deep.equal(0); + 'blackBoxObject.foo': 'bar' + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(schema, { $set: { - 'blackBoxObject.1': 'bar', - }, - }, { modifier: true }).to.deep.equal(0); - }); + 'blackBoxObject.1': 'bar' + } + }, { modifier: true }).to.deep.equal(0) + }) it('allows to $push into any subobject', function () { expectErrorLength(schema, { $push: { - 'blackBoxObject.foo': 'bar', - }, - }, { modifier: true }).to.deep.equal(0); - }); -}); + 'blackBoxObject.foo': 'bar' + } + }, { modifier: true }).to.deep.equal(0) + }) +}) diff --git a/lib/SimpleSchema_custom.tests.js b/lib/SimpleSchema_custom.tests.js index 7ae14d8..9a900c5 100644 --- a/lib/SimpleSchema_custom.tests.js +++ b/lib/SimpleSchema_custom.tests.js @@ -1,183 +1,183 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema, ValidationContext } from './SimpleSchema'; -import expectErrorLength from './testHelpers/expectErrorLength'; -import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength'; +import { expect } from 'chai' +import { SimpleSchema, ValidationContext } from './SimpleSchema' +import expectErrorLength from './testHelpers/expectErrorLength' +import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength' const schema = new SimpleSchema({ password: { - type: String, + type: String }, confirmPassword: { type: String, - custom() { + custom () { if (this.value !== this.field('password').value) { - return 'passwordMismatch'; + return 'passwordMismatch' } - }, - }, -}); + } + } +}) const requiredCustomSchema = new SimpleSchema({ a: { type: Array, - custom() { + custom () { // Just adding custom to trigger extra validation - }, + } }, 'a.$': { type: Object, - custom() { + custom () { // Just adding custom to trigger extra validation - }, + } }, b: { type: Array, - custom() { + custom () { // Just adding custom to trigger extra validation - }, + } }, 'b.$': { type: Object, - custom() { + custom () { // Just adding custom to trigger extra validation - }, - }, -}); + } + } +}) describe('SimpleSchema - Validation Against Another Key', function () { describe('normal', function () { it('valid', function () { expectErrorLength(schema, { password: 'password', - confirmPassword: 'password', - }).to.deep.equal(0); - }); + confirmPassword: 'password' + }).to.deep.equal(0) + }) it('invalid', function () { expectErrorOfTypeLength('passwordMismatch', schema, { password: 'password', - confirmPassword: 'password1', - }).to.deep.equal(1); - }); - }); + confirmPassword: 'password1' + }).to.deep.equal(1) + }) + }) describe('modifier with $setOnInsert', function () { it('valid', function () { expectErrorLength(schema, { $setOnInsert: { password: 'password', - confirmPassword: 'password', - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); - }); + confirmPassword: 'password' + } + }, { modifier: true, upsert: true }).to.deep.equal(0) + }) it('invalid', function () { expectErrorOfTypeLength('passwordMismatch', schema, { $setOnInsert: { password: 'password', - confirmPassword: 'password1', - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); - }); + confirmPassword: 'password1' + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) + }) describe('modifier with $set', function () { it('valid', function () { expectErrorLength(schema, { $set: { password: 'password', - confirmPassword: 'password', - }, - }, { modifier: true }).to.deep.equal(0); - }); + confirmPassword: 'password' + } + }, { modifier: true }).to.deep.equal(0) + }) it('invalid', function () { expectErrorOfTypeLength('passwordMismatch', schema, { $set: { password: 'password', - confirmPassword: 'password1', - }, - }, { modifier: true }).to.deep.equal(1); - }); - }); -}); + confirmPassword: 'password1' + } + }, { modifier: true }).to.deep.equal(1) + }) + }) +}) describe('custom', function () { it('custom validator has this.validationContext set', function () { - let ok = false; + let ok = false const customSchema = new SimpleSchema({ foo: { type: String, optional: true, - custom() { - if (this.validationContext instanceof ValidationContext) ok = true; - }, - }, - }); + custom () { + if (this.validationContext instanceof ValidationContext) ok = true + } + } + }) - customSchema.namedContext().validate({}); - expect(ok).to.equal(true); - }); + customSchema.namedContext().validate({}) + expect(ok).to.equal(true) + }) it('custom validation runs even when the optional field is undefined', function () { const customSchema = new SimpleSchema({ foo: { type: String, optional: true, - custom: () => 'custom', - }, - }); + custom: () => 'custom' + } + }) - const context = customSchema.namedContext(); - context.validate({}); - expect(context.validationErrors().length).to.deep.equal(1); - expect(context.validationErrors()[0]).to.deep.equal({ name: 'foo', type: 'custom', value: undefined }); - }); + const context = customSchema.namedContext() + context.validate({}) + expect(context.validationErrors().length).to.deep.equal(1) + expect(context.validationErrors()[0]).to.deep.equal({ name: 'foo', type: 'custom', value: undefined }) + }) it('custom validation runs when string is unset', function () { const customSchema = new SimpleSchema({ foo: { type: String, optional: true, - custom: () => 'custom', - }, - }); + custom: () => 'custom' + } + }) - const context = customSchema.namedContext(); + const context = customSchema.namedContext() context.validate({ $unset: { - foo: '', - }, - }, { modifier: true }); - expect(context.validationErrors().length).to.deep.equal(1); - expect(context.validationErrors()[0]).to.deep.equal({ name: 'foo', type: 'custom', value: '' }); - }); + foo: '' + } + }, { modifier: true }) + expect(context.validationErrors().length).to.deep.equal(1) + expect(context.validationErrors()[0]).to.deep.equal({ name: 'foo', type: 'custom', value: '' }) + }) it('we do not get required errors for a required field that has a `custom` function when we are $setting', function () { - const context = requiredCustomSchema.namedContext(); + const context = requiredCustomSchema.namedContext() expect(context.validate({ $set: { - a: [{}], - }, - }, { modifier: true })).to.deep.equal(true); + a: [{}] + } + }, { modifier: true })).to.deep.equal(true) expect(context.validate({ $set: { - 'a.0': {}, - }, - }, { modifier: true })).to.deep.equal(true); - }); + 'a.0': {} + } + }, { modifier: true })).to.deep.equal(true) + }) it('we do not get required errors for a required field that has a `custom` function when we are $pushing', function () { - const context = requiredCustomSchema.namedContext(); + const context = requiredCustomSchema.namedContext() expect(context.validate({ $push: { - a: {}, - }, - }, { modifier: true })).to.deep.equal(true); - }); -}); + a: {} + } + }, { modifier: true })).to.deep.equal(true) + }) +}) diff --git a/lib/SimpleSchema_definition.tests.js b/lib/SimpleSchema_definition.tests.js index 3405dc2..a731544 100644 --- a/lib/SimpleSchema_definition.tests.js +++ b/lib/SimpleSchema_definition.tests.js @@ -1,7 +1,7 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema, schemaDefinitionOptions } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema, schemaDefinitionOptions } from './SimpleSchema' describe('SimpleSchema - Extend Schema Definition', function () { it('throws an error when the schema definition includes an unrecognized key', function () { @@ -9,25 +9,25 @@ describe('SimpleSchema - Extend Schema Definition', function () { const schema = new SimpleSchema({ // eslint-disable-line no-unused-vars name: { type: String, - unique: true, - }, - }); - }).to.throw(); - }); + unique: true + } + }) + }).to.throw() + }) it('does not throw an error when the schema definition includes a registered key', function () { - SimpleSchema.extendOptions({ unique: true }); + SimpleSchema.extendOptions({ unique: true }) expect(() => { const schema = new SimpleSchema({ // eslint-disable-line no-unused-vars name: { type: String, - unique: true, - }, - }); - }).not.to.throw(); + unique: true + } + }) + }).not.to.throw() // Reset - schemaDefinitionOptions.splice(schemaDefinitionOptions.indexOf('unique'), 1); - }); -}); + schemaDefinitionOptions.splice(schemaDefinitionOptions.indexOf('unique'), 1) + }) +}) diff --git a/lib/SimpleSchema_extend.tests.js b/lib/SimpleSchema_extend.tests.js index ea381e4..2cfdb36 100644 --- a/lib/SimpleSchema_extend.tests.js +++ b/lib/SimpleSchema_extend.tests.js @@ -1,260 +1,260 @@ -import { expect } from 'chai'; -import { SimpleSchema, schemaDefinitionOptions } from './SimpleSchema'; -import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' +import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength' describe('SimpleSchema - Extend Schema', function () { it('supports extending with no type', function () { const schema = new SimpleSchema({ name: { type: String, - min: 5, - }, - }); + min: 5 + } + }) schema.extend({ name: { - max: 15, - }, - }); - expect(schema.get('name', 'max')).to.equal(15); - }); + max: 15 + } + }) + expect(schema.get('name', 'max')).to.equal(15) + }) it('updates blackbox keys after extending', function () { const schema = new SimpleSchema({ apple: { type: Object, - blackbox: true, + blackbox: true }, pear: new SimpleSchema({ info: { type: Object, - blackbox: true, - }, - }), - }); + blackbox: true + } + }) + }) schema.extend({ - pear: String, - }); + pear: String + }) - expect(schema.blackboxKeys()).to.deep.equal(['apple']); - }); + expect(schema.blackboxKeys()).to.deep.equal(['apple']) + }) it('works for plain objects', function () { const schema = new SimpleSchema({ firstName: { type: String, label: 'First name', - optional: false, + optional: false }, lastName: { type: String, label: 'Last name', - optional: false, - }, - }); + optional: false + } + }) schema.extend({ firstName: { - optional: true, - }, - }); + optional: true + } + }) expect(schema.schema()).to.deep.equal({ firstName: { type: SimpleSchema.oneOf(String), label: 'First name', - optional: true, + optional: true }, lastName: { type: SimpleSchema.oneOf(String), label: 'Last name', - optional: false, - }, - }); - }); + optional: false + } + }) + }) it('works for another SimpleSchema instance and copies validators', function () { const schema1 = new SimpleSchema({ firstName: { type: String, label: 'First name', - optional: false, + optional: false }, lastName: { type: String, label: 'Last name', - optional: false, - }, - }); + optional: false + } + }) const schema2 = new SimpleSchema({ age: { type: Number, - label: 'Age', - }, - }); - schema2.addValidator(() => {}); - schema2.addDocValidator(() => {}); + label: 'Age' + } + }) + schema2.addValidator(() => {}) + schema2.addDocValidator(() => {}) expect(schema1.schema()).to.deep.equal({ firstName: { type: SimpleSchema.oneOf(String), label: 'First name', - optional: false, + optional: false }, lastName: { type: SimpleSchema.oneOf(String), label: 'Last name', - optional: false, - }, - }); - expect(schema1._validators.length).to.equal(0); - expect(schema1._docValidators.length).to.equal(0); + optional: false + } + }) + expect(schema1._validators.length).to.equal(0) + expect(schema1._docValidators.length).to.equal(0) - schema1.extend(schema2); + schema1.extend(schema2) expect(schema1.schema()).to.deep.equal({ firstName: { type: SimpleSchema.oneOf(String), label: 'First name', - optional: false, + optional: false }, lastName: { type: SimpleSchema.oneOf(String), label: 'Last name', - optional: false, + optional: false }, age: { type: SimpleSchema.oneOf(Number), label: 'Age', - optional: false, - }, - }); - expect(schema1._validators.length).to.equal(1); - expect(schema1._docValidators.length).to.equal(1); - }); + optional: false + } + }) + expect(schema1._validators.length).to.equal(1) + expect(schema1._docValidators.length).to.equal(1) + }) it('keeps both min and max', function () { const schema = new SimpleSchema({ name: { type: String, - min: 5, - }, - }); + min: 5 + } + }) schema.extend({ name: { type: String, - max: 15, - }, - }); + max: 15 + } + }) - expect(schema._schema.name.type.definitions[0].min).to.equal(5); - expect(schema._schema.name.type.definitions[0].max).to.equal(15); - }); + expect(schema._schema.name.type.definitions[0].min).to.equal(5) + expect(schema._schema.name.type.definitions[0].max).to.equal(15) + }) it('does not mutate a schema that is passed to extend', function () { const itemSchema = new SimpleSchema({ - _id: String, - }); + _id: String + }) const mainSchema = new SimpleSchema({ items: Array, - 'items.$': itemSchema, - }); + 'items.$': itemSchema + }) const item2Schema = new SimpleSchema({ - blah: String, - }); + blah: String + }) const main2Schema = new SimpleSchema({ items: Array, - 'items.$': item2Schema, - }); + 'items.$': item2Schema + }) - new SimpleSchema({}).extend(mainSchema).extend(main2Schema); + new SimpleSchema({}).extend(mainSchema).extend(main2Schema) - expect(mainSchema._schema['items.$'].type.definitions[0].type._schemaKeys).to.deep.equal(['_id']); - }); + expect(mainSchema._schema['items.$'].type.definitions[0].type._schemaKeys).to.deep.equal(['_id']) + }) it('can extend array definition only, without array item definition', function () { const schema = new SimpleSchema({ myArray: { - type: Array, + type: Array }, 'myArray.$': { type: String, - allowedValues: ['foo', 'bar'], - }, - }); + allowedValues: ['foo', 'bar'] + } + }) - expect(schema._schema.myArray.type.definitions[0].minCount).to.equal(undefined); + expect(schema._schema.myArray.type.definitions[0].minCount).to.equal(undefined) schema.extend({ myArray: { - minCount: 1, - }, - }); + minCount: 1 + } + }) - expect(schema._schema.myArray.type.definitions[0].minCount).to.equal(1); - }); + expect(schema._schema.myArray.type.definitions[0].minCount).to.equal(1) + }) it('tests requiredness on fields added through extension', function () { const subitemSchema = new SimpleSchema({ - name: String, - }); + name: String + }) const itemSchema = new SimpleSchema({ name: String, subitems: { type: Array, - optional: true, + optional: true }, 'subitems.$': { - type: subitemSchema, - }, - }); + type: subitemSchema + } + }) const schema = new SimpleSchema({ name: String, items: { type: Array, - optional: true, + optional: true }, 'items.$': { - type: itemSchema, - }, - }); + type: itemSchema + } + }) subitemSchema.extend({ - other: String, - }); + other: String + }) expectErrorOfTypeLength(SimpleSchema.ErrorTypes.REQUIRED, schema, { name: 'foo', items: [{ name: 'foo', subitems: [{ - name: 'foo', - }], - }], - }).to.equal(1); - }); + name: 'foo' + }] + }] + }).to.equal(1) + }) it('gets correct objectKeys from extended subschemas', function () { const itemSchema = new SimpleSchema({ - name: String, - }); + name: String + }) const schema = new SimpleSchema({ name: String, - item: itemSchema, - }); + item: itemSchema + }) itemSchema.extend({ - other: String, - }); + other: String + }) - expect(schema.objectKeys()).to.deep.equal(['name', 'item']); - expect(schema.objectKeys('item')).to.deep.equal(['name', 'other']); - }); + expect(schema.objectKeys()).to.deep.equal(['name', 'item']) + expect(schema.objectKeys('item')).to.deep.equal(['name', 'other']) + }) it('supports extending allowedValues', function () { const ObjSchema = new SimpleSchema({ @@ -262,7 +262,7 @@ describe('SimpleSchema - Extend Schema', function () { type: String, allowedValues: ['platonic'] } - }); + }) const ListItemSchema = new SimpleSchema({ name: { @@ -273,47 +273,47 @@ describe('SimpleSchema - Extend Schema', function () { type: Object, blackbox: true } - }); + }) const schema = new SimpleSchema({ - 'list': { + list: { type: Array }, 'list.$': { type: ListItemSchema }, - 'primary': ObjSchema, - 'method': { + primary: ObjSchema, + method: { type: String, allowedValues: ['none', 'some'] - }, - }); + } + }) // Top-level field extension schema.extend({ method: { allowedValues: [...schema.getAllowedValuesForKey('method'), 'all'] - }, - }); + } + }) - expect(schema.getAllowedValuesForKey('method')).to.deep.equal(['none', 'some', 'all']); + expect(schema.getAllowedValuesForKey('method')).to.deep.equal(['none', 'some', 'all']) // Subschema field extension ObjSchema.extend({ loveType: { allowedValues: [...ObjSchema.getAllowedValuesForKey('loveType'), 'romantic'] - }, - }); + } + }) - expect(schema.getAllowedValuesForKey('primary.loveType')).to.deep.equal(['platonic', 'romantic']); + expect(schema.getAllowedValuesForKey('primary.loveType')).to.deep.equal(['platonic', 'romantic']) // Subschema field in array field extension ListItemSchema.extend({ name: { allowedValues: [...ListItemSchema.getAllowedValuesForKey('name'), 'b', 'c'] - }, - }); + } + }) - expect(schema.getAllowedValuesForKey('list.$.name')).to.deep.equal(['a', 'b', 'c']); - }); -}); + expect(schema.getAllowedValuesForKey('list.$.name')).to.deep.equal(['a', 'b', 'c']) + }) +}) diff --git a/lib/SimpleSchema_getObjectSchema.tests.js b/lib/SimpleSchema_getObjectSchema.tests.js index db27d43..dfe02b1 100644 --- a/lib/SimpleSchema_getObjectSchema.tests.js +++ b/lib/SimpleSchema_getObjectSchema.tests.js @@ -1,7 +1,7 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema', function () { describe('getObjectSchema', function () { @@ -10,132 +10,132 @@ describe('SimpleSchema', function () { foo: Object, 'foo.aaa': { type: String, - optional: true, + optional: true }, 'foo.bbb': { type: Object, - optional: true, + optional: true }, 'foo.bbb.zzz': { - type: Number, - }, - }); + type: Number + } + }) - const newSchema = schema.getObjectSchema('foo'); + const newSchema = schema.getObjectSchema('foo') expect(newSchema.mergedSchema()).to.deep.equal({ aaa: { type: SimpleSchema.oneOf(String), label: 'Aaa', - optional: true, + optional: true }, bbb: { type: SimpleSchema.oneOf(Object), label: 'Bbb', - optional: true, + optional: true }, 'bbb.zzz': { type: SimpleSchema.oneOf(Number), label: 'Zzz', - optional: false, - }, - }); - }); + optional: false + } + }) + }) it('second level object', function () { const schema = new SimpleSchema({ foo: Object, 'foo.aaa': { type: String, - optional: true, + optional: true }, 'foo.bbb': { type: Object, - optional: true, + optional: true }, 'foo.bbb.zzz': { - type: Number, - }, - }); + type: Number + } + }) - const newSchema = schema.getObjectSchema('foo.bbb'); + const newSchema = schema.getObjectSchema('foo.bbb') expect(newSchema.mergedSchema()).to.deep.equal({ zzz: { type: SimpleSchema.oneOf(Number), label: 'Zzz', - optional: false, - }, - }); - }); + optional: false + } + }) + }) it('object in array', function () { const schema = new SimpleSchema({ foo: Object, 'foo.aaa': { type: Array, - optional: true, + optional: true }, 'foo.aaa.$': { - type: Object, + type: Object }, 'foo.aaa.$.zzz': { type: String, - optional: true, + optional: true }, 'foo.aaa.$.yyy': { - type: Boolean, - }, - }); + type: Boolean + } + }) - const newSchema = schema.getObjectSchema('foo.aaa.$'); + const newSchema = schema.getObjectSchema('foo.aaa.$') expect(newSchema.mergedSchema()).to.deep.equal({ zzz: { type: SimpleSchema.oneOf(String), label: 'Zzz', - optional: true, + optional: true }, yyy: { type: SimpleSchema.oneOf(Boolean), label: 'Yyy', - optional: false, - }, - }); - }); + optional: false + } + }) + }) it('subschema', function () { const schema = new SimpleSchema({ foo: new SimpleSchema({ aaa: { type: String, - optional: true, + optional: true }, bbb: { type: Object, - optional: true, + optional: true }, 'bbb.zzz': { - type: Number, - }, - }), - }); + type: Number + } + }) + }) - const newSchema = schema.getObjectSchema('foo'); + const newSchema = schema.getObjectSchema('foo') expect(newSchema.mergedSchema()).to.deep.equal({ aaa: { type: SimpleSchema.oneOf(String), label: 'Aaa', - optional: true, + optional: true }, bbb: { type: SimpleSchema.oneOf(Object), label: 'Bbb', - optional: true, + optional: true }, 'bbb.zzz': { type: SimpleSchema.oneOf(Number), label: 'Zzz', - optional: false, - }, - }); - }); - }); -}); + optional: false + } + }) + }) + }) +}) diff --git a/lib/SimpleSchema_getQuickTypeForKey.tests.js b/lib/SimpleSchema_getQuickTypeForKey.tests.js index fbba923..dd8bc5c 100644 --- a/lib/SimpleSchema_getQuickTypeForKey.tests.js +++ b/lib/SimpleSchema_getQuickTypeForKey.tests.js @@ -1,129 +1,129 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema', function () { describe('getQuickTypeForKey', function () { it('string', function () { const schema = new SimpleSchema({ - foo: String, - }); + foo: String + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('string'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('string') + }) it('number', function () { const schema = new SimpleSchema({ - foo: Number, - }); + foo: Number + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('number'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('number') + }) it('int', function () { const schema = new SimpleSchema({ - foo: SimpleSchema.Integer, - }); + foo: SimpleSchema.Integer + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('number'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('number') + }) it('boolean', function () { const schema = new SimpleSchema({ - foo: Boolean, - }); + foo: Boolean + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('boolean'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('boolean') + }) it('date', function () { const schema = new SimpleSchema({ - foo: Date, - }); + foo: Date + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('date'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('date') + }) it('object', function () { const schema = new SimpleSchema({ - foo: Object, - }); + foo: Object + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('object'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('object') + }) it('stringArray', function () { const schema = new SimpleSchema({ - foo: [String], - }); + foo: [String] + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('stringArray'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('stringArray') + }) it('numberArray', function () { const schema = new SimpleSchema({ - foo: [Number], - }); + foo: [Number] + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('numberArray'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('numberArray') + }) it('int array', function () { const schema = new SimpleSchema({ - foo: [SimpleSchema.Integer], - }); + foo: [SimpleSchema.Integer] + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('numberArray'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('numberArray') + }) it('booleanArray', function () { const schema = new SimpleSchema({ - foo: [Boolean], - }); + foo: [Boolean] + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('booleanArray'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('booleanArray') + }) it('dateArray', function () { const schema = new SimpleSchema({ - foo: [Date], - }); + foo: [Date] + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('dateArray'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('dateArray') + }) it('objectArray', function () { const schema = new SimpleSchema({ - foo: [Object], - }); + foo: [Object] + }) - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('objectArray'); - }); + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('objectArray') + }) it('objectArray (subschema)', function () { const subschema = new SimpleSchema({ - bar: String, - }); + bar: String + }) const schema = new SimpleSchema({ - foo: [subschema], - }); - - const type = schema.getQuickTypeForKey('foo'); - expect(type).to.equal('objectArray'); - }); - }); -}); + foo: [subschema] + }) + + const type = schema.getQuickTypeForKey('foo') + expect(type).to.equal('objectArray') + }) + }) +}) diff --git a/lib/SimpleSchema_labels.tests.js b/lib/SimpleSchema_labels.tests.js index 131ce7a..fc31fa7 100644 --- a/lib/SimpleSchema_labels.tests.js +++ b/lib/SimpleSchema_labels.tests.js @@ -1,77 +1,77 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema - label', function () { it('inflection', function () { const schema = new SimpleSchema({ minMaxNumber: { type: SimpleSchema.Integer }, obj: { type: Object }, - 'obj.someString': { type: String }, - }); + 'obj.someString': { type: String } + }) - expect(schema.label('minMaxNumber')).to.equal('Min max number'); - expect(schema.label('obj.someString')).to.equal('Some string'); - }); + expect(schema.label('minMaxNumber')).to.equal('Min max number') + expect(schema.label('obj.someString')).to.equal('Some string') + }) it('dynamic', function () { const schema = new SimpleSchema({ minMaxNumber: { type: SimpleSchema.Integer }, obj: { type: Object }, - 'obj.someString': { type: String }, - }); + 'obj.someString': { type: String } + }) - expect(schema.label('obj.someString')).to.equal('Some string'); + expect(schema.label('obj.someString')).to.equal('Some string') schema.labels({ - 'obj.someString': 'A different label', - }); + 'obj.someString': 'A different label' + }) - expect(schema.label('obj.someString')).to.equal('A different label'); - }); + expect(schema.label('obj.someString')).to.equal('A different label') + }) it('callback', function () { const schema = new SimpleSchema({ minMaxNumber: { type: SimpleSchema.Integer }, obj: { type: Object }, - 'obj.someString': { type: String }, - }); + 'obj.someString': { type: String } + }) - expect(schema.label('obj.someString')).to.equal('Some string'); + expect(schema.label('obj.someString')).to.equal('Some string') schema.labels({ - 'obj.someString': () => 'A callback label', - }); + 'obj.someString': () => 'A callback label' + }) - expect(schema.label('obj.someString')).to.equal('A callback label'); - }); + expect(schema.label('obj.someString')).to.equal('A callback label') + }) it('should allow apostrophes ("\'") in labels', () => { const schema = new SimpleSchema({ foo: { type: String, - label: 'Manager/supervisor\'s name', - }, - }); - expect(schema.label('foo')).to.equal('Manager/supervisor\'s name'); - }); + label: 'Manager/supervisor\'s name' + } + }) + expect(schema.label('foo')).to.equal('Manager/supervisor\'s name') + }) it('can set label of field in nested schema', function () { const objSchema = new SimpleSchema({ - someString: String, - }); + someString: String + }) const schema = new SimpleSchema({ - obj: objSchema, - }); + obj: objSchema + }) - expect(schema.label('obj.someString')).to.equal('Some string'); + expect(schema.label('obj.someString')).to.equal('Some string') schema.labels({ - 'obj.someString': 'New label', - }); + 'obj.someString': 'New label' + }) - expect(schema.label('obj.someString')).to.equal('New label'); - }); -}); + expect(schema.label('obj.someString')).to.equal('New label') + }) +}) diff --git a/lib/SimpleSchema_max.tests.js b/lib/SimpleSchema_max.tests.js index 56ffc0f..3ba9c79 100644 --- a/lib/SimpleSchema_max.tests.js +++ b/lib/SimpleSchema_max.tests.js @@ -1,256 +1,256 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import testSchema from './testHelpers/testSchema'; -import friendsSchema from './testHelpers/friendsSchema'; -import expectErrorLength from './testHelpers/expectErrorLength'; -import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength'; -import { SimpleSchema } from './SimpleSchema'; +import testSchema from './testHelpers/testSchema' +import friendsSchema from './testHelpers/friendsSchema' +import expectErrorLength from './testHelpers/expectErrorLength' +import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema - max', function () { describe('normal', function () { it('string', function () { expectErrorLength(testSchema, { - minMaxString: 'nottoolongnottoolong', - }).to.deep.equal(0); + minMaxString: 'nottoolongnottoolong' + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxString: 'toolongtoolongtoolong', - }).to.deep.equal(1); + minMaxString: 'toolongtoolongtoolong' + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong'], - }).to.deep.equal(0); + minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong'] + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxStringArray: ['toolongtoolongtoolong', 'toolongtoolongtoolong'], - }).to.deep.equal(2); + minMaxStringArray: ['toolongtoolongtoolong', 'toolongtoolongtoolong'] + }).to.deep.equal(2) expectErrorLength(testSchema, { - minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong', 'nottoolongnottoolong'], - }).to.deep.equal(1); - }); + minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong', 'nottoolongnottoolong'] + }).to.deep.equal(1) + }) it('number', function () { expectErrorLength(testSchema, { - minMaxNumber: 20, - }).to.deep.equal(0); + minMaxNumber: 20 + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxNumber: 21, - }).to.deep.equal(1); + minMaxNumber: 21 + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxNumberCalculated: 20, - }).to.deep.equal(0); + minMaxNumberCalculated: 20 + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxNumberCalculated: 21, - }).to.deep.equal(1); - }); + minMaxNumberCalculated: 21 + }).to.deep.equal(1) + }) it('date', function () { expectErrorLength(testSchema, { - minMaxDate: (new Date(Date.UTC(2013, 11, 31))), - }).to.deep.equal(0); + minMaxDate: (new Date(Date.UTC(2013, 11, 31))) + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxDate: (new Date(Date.UTC(2014, 0, 1))), - }).to.deep.equal(1); + minMaxDate: (new Date(Date.UTC(2014, 0, 1))) + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxDateCalculated: (new Date(Date.UTC(2013, 11, 31))), - }).to.deep.equal(0); + minMaxDateCalculated: (new Date(Date.UTC(2013, 11, 31))) + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxDateCalculated: (new Date(Date.UTC(2014, 0, 1))), - }).to.deep.equal(1); - }); - }); + minMaxDateCalculated: (new Date(Date.UTC(2014, 0, 1))) + }).to.deep.equal(1) + }) + }) describe('modifier with $setOnInsert', function () { it('string', function () { expectErrorLength(testSchema, { $setOnInsert: { - minMaxString: 'nottoolongnottoolong', - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxString: 'nottoolongnottoolong' + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxString: 'toolongtoolongtoolong', - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + minMaxString: 'toolongtoolongtoolong' + } + }, { modifier: true, upsert: true }).to.deep.equal(1) expectErrorLength(testSchema, { $setOnInsert: { - minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong'] + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxStringArray: ['toolongtoolongtoolong', 'toolongtoolongtoolong'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(2); + minMaxStringArray: ['toolongtoolongtoolong', 'toolongtoolongtoolong'] + } + }, { modifier: true, upsert: true }).to.deep.equal(2) expectErrorLength(testSchema, { $setOnInsert: { - minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong', 'nottoolongnottoolong'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); + minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong', 'nottoolongnottoolong'] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) it('number', function () { expectErrorLength(testSchema, { $setOnInsert: { - minMaxNumber: 20, - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxNumber: 20 + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxNumber: 21, - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + minMaxNumber: 21 + } + }, { modifier: true, upsert: true }).to.deep.equal(1) expectErrorLength(testSchema, { $setOnInsert: { - minMaxNumberCalculated: 20, - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxNumberCalculated: 20 + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxNumberCalculated: 21, - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); + minMaxNumberCalculated: 21 + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) it('date', function () { expectErrorLength(testSchema, { $setOnInsert: { - minMaxDate: (new Date(Date.UTC(2013, 11, 31))), - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxDate: (new Date(Date.UTC(2013, 11, 31))) + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxDate: (new Date(Date.UTC(2014, 0, 1))), - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + minMaxDate: (new Date(Date.UTC(2014, 0, 1))) + } + }, { modifier: true, upsert: true }).to.deep.equal(1) expectErrorLength(testSchema, { $setOnInsert: { - minMaxDateCalculated: (new Date(Date.UTC(2013, 11, 31))), - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxDateCalculated: (new Date(Date.UTC(2013, 11, 31))) + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxDateCalculated: (new Date(Date.UTC(2014, 0, 1))), - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); - }); + minMaxDateCalculated: (new Date(Date.UTC(2014, 0, 1))) + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) + }) describe('modifier with $set or $inc', function () { it('string', function () { expectErrorLength(testSchema, { $set: { - minMaxString: 'nottoolongnottoolong', - }, - }, { modifier: true }).to.deep.equal(0); + minMaxString: 'nottoolongnottoolong' + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxString: 'toolongtoolongtoolong', - }, - }, { modifier: true }).to.deep.equal(1); + minMaxString: 'toolongtoolongtoolong' + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong'], - }, - }, { modifier: true }).to.deep.equal(0); + minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong'] + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxStringArray: ['toolongtoolongtoolong', 'toolongtoolongtoolong'], - }, - }, { modifier: true }).to.deep.equal(2); + minMaxStringArray: ['toolongtoolongtoolong', 'toolongtoolongtoolong'] + } + }, { modifier: true }).to.deep.equal(2) expectErrorLength(testSchema, { $set: { - minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong', 'nottoolongnottoolong'], - }, - }, { modifier: true }).to.deep.equal(1); - }); + minMaxStringArray: ['nottoolongnottoolong', 'nottoolongnottoolong', 'nottoolongnottoolong'] + } + }, { modifier: true }).to.deep.equal(1) + }) it('number', function () { expectErrorLength(testSchema, { $set: { - minMaxNumber: 20, - }, - }, { modifier: true }).to.deep.equal(0); + minMaxNumber: 20 + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxNumber: 21, - }, - }, { modifier: true }).to.deep.equal(1); + minMaxNumber: 21 + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - minMaxNumberCalculated: 20, - }, - }, { modifier: true }).to.deep.equal(0); + minMaxNumberCalculated: 20 + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxNumberCalculated: 21, - }, - }, { modifier: true }).to.deep.equal(1); + minMaxNumberCalculated: 21 + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - maxZero: 1, - }, - }, { modifier: true }).to.deep.equal(1); + maxZero: 1 + } + }, { modifier: true }).to.deep.equal(1) // Should not be invalid because we don't know what we're starting from expectErrorLength(testSchema, { $inc: { - maxZero: 5, - }, - }, { modifier: true }).to.deep.equal(0); - }); + maxZero: 5 + } + }, { modifier: true }).to.deep.equal(0) + }) it('date', function () { expectErrorLength(testSchema, { $set: { - minMaxDate: (new Date(Date.UTC(2013, 11, 31))), - }, - }, { modifier: true }).to.deep.equal(0); + minMaxDate: (new Date(Date.UTC(2013, 11, 31))) + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxDate: (new Date(Date.UTC(2014, 0, 1))), - }, - }, { modifier: true }).to.deep.equal(1); + minMaxDate: (new Date(Date.UTC(2014, 0, 1))) + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - minMaxDateCalculated: (new Date(Date.UTC(2013, 11, 31))), - }, - }, { modifier: true }).to.deep.equal(0); + minMaxDateCalculated: (new Date(Date.UTC(2013, 11, 31))) + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxDateCalculated: (new Date(Date.UTC(2014, 0, 1))), - }, - }, { modifier: true }).to.deep.equal(1); - }); - }); + minMaxDateCalculated: (new Date(Date.UTC(2014, 0, 1))) + } + }, { modifier: true }).to.deep.equal(1) + }) + }) describe('modifier with $push', function () { it('valid', function () { @@ -258,23 +258,23 @@ describe('SimpleSchema - max', function () { $push: { friends: { name: 'Bob', - type: 'best', - }, - }, - }, { modifier: true }).to.deep.equal(0); - }); + type: 'best' + } + } + }, { modifier: true }).to.deep.equal(0) + }) it('invalid', function () { expectErrorOfTypeLength(SimpleSchema.ErrorTypes.MAX_STRING, friendsSchema, { $push: { friends: { name: 'Bobby', - type: 'best', - }, - }, - }, { modifier: true }).to.deep.equal(1); - }); - }); + type: 'best' + } + } + }, { modifier: true }).to.deep.equal(1) + }) + }) describe('modifier with $push and $each', function () { it('valid', function () { @@ -283,15 +283,15 @@ describe('SimpleSchema - max', function () { friends: { $each: [{ name: 'Bob', - type: 'best', + type: 'best' }, { name: 'Bob', - type: 'best', - }], - }, - }, - }, { modifier: true }).to.deep.equal(0); - }); + type: 'best' + }] + } + } + }, { modifier: true }).to.deep.equal(0) + }) it('invalid', function () { expectErrorOfTypeLength(SimpleSchema.ErrorTypes.MAX_STRING, friendsSchema, { @@ -299,16 +299,16 @@ describe('SimpleSchema - max', function () { friends: { $each: [{ name: 'Bob', - type: 'best', + type: 'best' }, { name: 'Bobby', - type: 'best', - }], - }, - }, - }, { modifier: true }).to.deep.equal(1); - }); - }); + type: 'best' + }] + } + } + }, { modifier: true }).to.deep.equal(1) + }) + }) describe('modifier with $addToSet', function () { it('valid', function () { @@ -316,23 +316,23 @@ describe('SimpleSchema - max', function () { $addToSet: { friends: { name: 'Bob', - type: 'best', - }, - }, - }, { modifier: true }).to.deep.equal(0); - }); + type: 'best' + } + } + }, { modifier: true }).to.deep.equal(0) + }) it('invalid', function () { expectErrorOfTypeLength(SimpleSchema.ErrorTypes.MAX_STRING, friendsSchema, { $addToSet: { friends: { name: 'Bobby', - type: 'best', - }, - }, - }, { modifier: true }).to.deep.equal(1); - }); - }); + type: 'best' + } + } + }, { modifier: true }).to.deep.equal(1) + }) + }) describe('modifier with $addToSet and $each', function () { it('valid', function () { @@ -341,15 +341,15 @@ describe('SimpleSchema - max', function () { friends: { $each: [{ name: 'Bob', - type: 'best', + type: 'best' }, { name: 'Bob', - type: 'best', - }], - }, - }, - }, { modifier: true }).to.deep.equal(0); - }); + type: 'best' + }] + } + } + }, { modifier: true }).to.deep.equal(0) + }) it('invalid', function () { expectErrorOfTypeLength(SimpleSchema.ErrorTypes.MAX_STRING, friendsSchema, { @@ -357,14 +357,14 @@ describe('SimpleSchema - max', function () { friends: { $each: [{ name: 'Bob', - type: 'best', + type: 'best' }, { name: 'Bobby', - type: 'best', - }], - }, - }, - }, { modifier: true }).to.deep.equal(1); - }); - }); -}); + type: 'best' + }] + } + } + }, { modifier: true }).to.deep.equal(1) + }) + }) +}) diff --git a/lib/SimpleSchema_messages.tests.js b/lib/SimpleSchema_messages.tests.js index 2b1c051..f08a095 100644 --- a/lib/SimpleSchema_messages.tests.js +++ b/lib/SimpleSchema_messages.tests.js @@ -1,301 +1,301 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema', function () { describe('messages', function () { it('required', function () { const schema = new SimpleSchema({ - foo: String, - }); + foo: String + }) - const context = schema.newContext(); - context.validate({}); - expect(context.keyErrorMessage('foo')).to.equal('Foo is required'); - }); + const context = schema.newContext() + context.validate({}) + expect(context.keyErrorMessage('foo')).to.equal('Foo is required') + }) it('minString', function () { const schema = new SimpleSchema({ foo: { type: String, - min: 2, - }, - }); + min: 2 + } + }) - const context = schema.newContext(); - context.validate({ foo: 'a' }); - expect(context.keyErrorMessage('foo')).to.equal('Foo must be at least 2 characters'); - }); + const context = schema.newContext() + context.validate({ foo: 'a' }) + expect(context.keyErrorMessage('foo')).to.equal('Foo must be at least 2 characters') + }) it('maxString', function () { const schema = new SimpleSchema({ foo: { type: String, - max: 2, - }, - }); + max: 2 + } + }) - const context = schema.newContext(); - context.validate({ foo: 'abc' }); - expect(context.keyErrorMessage('foo')).to.equal('Foo cannot exceed 2 characters'); - }); + const context = schema.newContext() + context.validate({ foo: 'abc' }) + expect(context.keyErrorMessage('foo')).to.equal('Foo cannot exceed 2 characters') + }) it('minNumber', function () { const schema = new SimpleSchema({ foo: { type: Number, - min: 2, - }, - }); + min: 2 + } + }) - const context = schema.newContext(); - context.validate({ foo: 1.5 }); - expect(context.keyErrorMessage('foo')).to.equal('Foo must be at least 2'); - }); + const context = schema.newContext() + context.validate({ foo: 1.5 }) + expect(context.keyErrorMessage('foo')).to.equal('Foo must be at least 2') + }) it('maxNumber', function () { const schema = new SimpleSchema({ foo: { type: Number, - max: 2, - }, - }); + max: 2 + } + }) - const context = schema.newContext(); - context.validate({ foo: 2.5 }); - expect(context.keyErrorMessage('foo')).to.equal('Foo cannot exceed 2'); - }); + const context = schema.newContext() + context.validate({ foo: 2.5 }) + expect(context.keyErrorMessage('foo')).to.equal('Foo cannot exceed 2') + }) it('minNumberExclusive', function () { const schema = new SimpleSchema({ foo: { type: Number, min: 2, - exclusiveMin: true, - }, - }); + exclusiveMin: true + } + }) - const context = schema.newContext(); - context.validate({ foo: 2 }); - expect(context.keyErrorMessage('foo')).to.equal('Foo must be greater than 2'); - }); + const context = schema.newContext() + context.validate({ foo: 2 }) + expect(context.keyErrorMessage('foo')).to.equal('Foo must be greater than 2') + }) it('maxNumberExclusive', function () { const schema = new SimpleSchema({ foo: { type: Number, max: 2, - exclusiveMax: true, - }, - }); + exclusiveMax: true + } + }) - const context = schema.newContext(); - context.validate({ foo: 2 }); - expect(context.keyErrorMessage('foo')).to.equal('Foo must be less than 2'); - }); + const context = schema.newContext() + context.validate({ foo: 2 }) + expect(context.keyErrorMessage('foo')).to.equal('Foo must be less than 2') + }) it('minDate', function () { const schema = new SimpleSchema({ foo: { type: Date, - min: new Date(Date.UTC(2015, 11, 15, 0, 0, 0, 0)), - }, - }); + min: new Date(Date.UTC(2015, 11, 15, 0, 0, 0, 0)) + } + }) - const context = schema.newContext(); - context.validate({ foo: new Date(Date.UTC(2015, 10, 15, 0, 0, 0, 0)) }); - expect(context.keyErrorMessage('foo')).to.equal('Foo must be on or after 2015-12-15'); - }); + const context = schema.newContext() + context.validate({ foo: new Date(Date.UTC(2015, 10, 15, 0, 0, 0, 0)) }) + expect(context.keyErrorMessage('foo')).to.equal('Foo must be on or after 2015-12-15') + }) it('maxDate', function () { const schema = new SimpleSchema({ foo: { type: Date, - max: new Date(Date.UTC(2015, 11, 15, 0, 0, 0, 0)), - }, - }); + max: new Date(Date.UTC(2015, 11, 15, 0, 0, 0, 0)) + } + }) - const context = schema.newContext(); - context.validate({ foo: new Date(Date.UTC(2016, 1, 15, 0, 0, 0, 0)) }); - expect(context.keyErrorMessage('foo')).to.equal('Foo cannot be after 2015-12-15'); - }); + const context = schema.newContext() + context.validate({ foo: new Date(Date.UTC(2016, 1, 15, 0, 0, 0, 0)) }) + expect(context.keyErrorMessage('foo')).to.equal('Foo cannot be after 2015-12-15') + }) it('badDate', function () { const schema = new SimpleSchema({ foo: { - type: Date, - }, - }); + type: Date + } + }) - const context = schema.newContext(); - context.validate({ foo: new Date('invalid') }); - expect(context.keyErrorMessage('foo')).to.equal('Foo is not a valid date'); - }); + const context = schema.newContext() + context.validate({ foo: new Date('invalid') }) + expect(context.keyErrorMessage('foo')).to.equal('Foo is not a valid date') + }) it('minCount', function () { const schema = new SimpleSchema({ foo: { type: Array, - minCount: 2, + minCount: 2 }, - 'foo.$': Number, - }); + 'foo.$': Number + }) - const context = schema.newContext(); - context.validate({ foo: [1] }); - expect(context.keyErrorMessage('foo')).to.equal('You must specify at least 2 values'); - }); + const context = schema.newContext() + context.validate({ foo: [1] }) + expect(context.keyErrorMessage('foo')).to.equal('You must specify at least 2 values') + }) it('maxCount', function () { const schema = new SimpleSchema({ foo: { type: Array, - maxCount: 2, + maxCount: 2 }, - 'foo.$': Number, - }); + 'foo.$': Number + }) - const context = schema.newContext(); - context.validate({ foo: [1, 2, 3] }); - expect(context.keyErrorMessage('foo')).to.equal('You cannot specify more than 2 values'); - }); + const context = schema.newContext() + context.validate({ foo: [1, 2, 3] }) + expect(context.keyErrorMessage('foo')).to.equal('You cannot specify more than 2 values') + }) it('noDecimal', function () { const schema = new SimpleSchema({ - foo: SimpleSchema.Integer, - }); + foo: SimpleSchema.Integer + }) - const context = schema.newContext(); - context.validate({ foo: 1.5 }); - expect(context.keyErrorMessage('foo')).to.equal('Foo must be an integer'); - }); + const context = schema.newContext() + context.validate({ foo: 1.5 }) + expect(context.keyErrorMessage('foo')).to.equal('Foo must be an integer') + }) it('notAllowed', function () { const schema = new SimpleSchema({ foo: { type: String, - allowedValues: ['a', 'b', 'c'], - }, - }); + allowedValues: ['a', 'b', 'c'] + } + }) - const context = schema.newContext(); - context.validate({ foo: 'd' }); - expect(context.keyErrorMessage('foo')).to.equal('d is not an allowed value'); - }); + const context = schema.newContext() + context.validate({ foo: 'd' }) + expect(context.keyErrorMessage('foo')).to.equal('d is not an allowed value') + }) it('expectedType', function () { const schema = new SimpleSchema({ - foo: String, - }); + foo: String + }) - const context = schema.newContext(); - context.validate({ foo: 1 }); - expect(context.keyErrorMessage('foo')).to.equal('Foo must be of type String'); - }); + const context = schema.newContext() + context.validate({ foo: 1 }) + expect(context.keyErrorMessage('foo')).to.equal('Foo must be of type String') + }) it('regEx built in', function () { const schema = new SimpleSchema({ foo: { type: String, - regEx: SimpleSchema.RegEx.Email, - }, - }); + regEx: SimpleSchema.RegEx.Email + } + }) - const context = schema.newContext(); - context.validate({ foo: 'abc' }); - expect(context.keyErrorMessage('foo')).to.equal('Foo must be a valid email address'); - }); + const context = schema.newContext() + context.validate({ foo: 'abc' }) + expect(context.keyErrorMessage('foo')).to.equal('Foo must be a valid email address') + }) it('regEx other', function () { const schema = new SimpleSchema({ foo: { type: String, - regEx: /def/g, - }, - }); + regEx: /def/g + } + }) - const context = schema.newContext(); - context.validate({ foo: 'abc' }); - expect(context.keyErrorMessage('foo')).to.equal('Foo failed regular expression validation'); - }); + const context = schema.newContext() + context.validate({ foo: 'abc' }) + expect(context.keyErrorMessage('foo')).to.equal('Foo failed regular expression validation') + }) describe('keyNotInSchema', function () { const schema = new SimpleSchema({ - foo: String, - }); + foo: String + }) it('normal', function () { - const context = schema.newContext(); - context.validate({ bar: 1 }); - expect(context.keyErrorMessage('bar')).to.equal('bar is not allowed by the schema'); - }); + const context = schema.newContext() + context.validate({ bar: 1 }) + expect(context.keyErrorMessage('bar')).to.equal('bar is not allowed by the schema') + }) it('$set', function () { - const context = schema.newContext(); + const context = schema.newContext() context.validate({ $set: { - bar: 1, - }, - }, { modifier: true }); - expect(context.keyErrorMessage('bar')).to.equal('bar is not allowed by the schema'); - }); + bar: 1 + } + }, { modifier: true }) + expect(context.keyErrorMessage('bar')).to.equal('bar is not allowed by the schema') + }) it('$unset does not complain', function () { - const context = schema.newContext(); + const context = schema.newContext() context.validate({ $unset: { - bar: '', - }, - }, { modifier: true }); - expect(context.isValid()).to.equal(true); - }); - }); + bar: '' + } + }, { modifier: true }) + expect(context.isValid()).to.equal(true) + }) + }) it('should allow labels with apostrophes ("\'") in messages', function () { const schema = new SimpleSchema({ foo: { type: String, - label: 'Manager/supervisor\'s name', - }, - }); + label: 'Manager/supervisor\'s name' + } + }) - const context = schema.newContext(); - context.validate({}); - expect(context.keyErrorMessage('foo')).to.equal('Manager/supervisor\'s name is required'); - }); - }); + const context = schema.newContext() + context.validate({}) + expect(context.keyErrorMessage('foo')).to.equal('Manager/supervisor\'s name is required') + }) + }) describe('multipleSchema', function () { const schema = new SimpleSchema({ - foo: String, - }); + foo: String + }) schema.messageBox.messages({ en: { required: { - foo: 'Your foo is required mate', - }, - }, - }); + foo: 'Your foo is required mate' + } + } + }) const schema2 = new SimpleSchema({ foo: String, - bar: Number, - }); + bar: Number + }) schema2.messageBox.messages({ en: { required: { - foo: 'Your bar is required for sure', - }, - }, - }); + foo: 'Your bar is required for sure' + } + } + }) it('should keep message boxes separate between objects', function () { - const context = schema.newContext(); - context.validate({}); - expect(context.keyErrorMessage('foo')).to.equal('Your foo is required mate'); - }); - }); -}); + const context = schema.newContext() + context.validate({}) + expect(context.keyErrorMessage('foo')).to.equal('Your foo is required mate') + }) + }) +}) diff --git a/lib/SimpleSchema_min.tests.js b/lib/SimpleSchema_min.tests.js index 32bbeb0..d8e16ec 100644 --- a/lib/SimpleSchema_min.tests.js +++ b/lib/SimpleSchema_min.tests.js @@ -1,281 +1,281 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import testSchema from './testHelpers/testSchema'; -import expectErrorLength from './testHelpers/expectErrorLength'; +import testSchema from './testHelpers/testSchema' +import expectErrorLength from './testHelpers/expectErrorLength' describe('SimpleSchema - min', function () { describe('normal', function () { it('string', function () { expectErrorLength(testSchema, { - minMaxString: 'longenough', - }).to.deep.equal(0); + minMaxString: 'longenough' + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxString: 'short', - }).to.deep.equal(1); + minMaxString: 'short' + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxString: '', - }).to.deep.equal(1); + minMaxString: '' + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxStringArray: ['longenough', 'longenough'], - }).to.deep.equal(0); + minMaxStringArray: ['longenough', 'longenough'] + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxStringArray: ['longenough', 'short'], - }).to.deep.equal(1); + minMaxStringArray: ['longenough', 'short'] + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxStringArray: ['short', 'short'], - }).to.deep.equal(2); - }); + minMaxStringArray: ['short', 'short'] + }).to.deep.equal(2) + }) it('number', function () { expectErrorLength(testSchema, { - minMaxNumberExclusive: 20, - }).to.deep.equal(1); + minMaxNumberExclusive: 20 + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxNumberExclusive: 10, - }).to.deep.equal(1); + minMaxNumberExclusive: 10 + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxNumberInclusive: 20, - }).to.deep.equal(0); + minMaxNumberInclusive: 20 + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxNumberInclusive: 10, - }).to.deep.equal(0); + minMaxNumberInclusive: 10 + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxNumber: 10, - }).to.deep.equal(0); + minMaxNumber: 10 + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxNumber: 9, - }).to.deep.equal(1); + minMaxNumber: 9 + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxNumberCalculated: 10, - }).to.deep.equal(0); + minMaxNumberCalculated: 10 + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxNumberCalculated: 9, - }).to.deep.equal(1); + minMaxNumberCalculated: 9 + }).to.deep.equal(1) expectErrorLength(testSchema, { - minZero: -1, - }).to.deep.equal(1); - }); + minZero: -1 + }).to.deep.equal(1) + }) it('date', function () { expectErrorLength(testSchema, { - minMaxDate: (new Date(Date.UTC(2013, 0, 1))), - }).to.deep.equal(0); + minMaxDate: (new Date(Date.UTC(2013, 0, 1))) + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxDate: (new Date(Date.UTC(2012, 11, 31))), - }).to.deep.equal(1); + minMaxDate: (new Date(Date.UTC(2012, 11, 31))) + }).to.deep.equal(1) expectErrorLength(testSchema, { - minMaxDateCalculated: (new Date(Date.UTC(2013, 0, 1))), - }).to.deep.equal(0); + minMaxDateCalculated: (new Date(Date.UTC(2013, 0, 1))) + }).to.deep.equal(0) expectErrorLength(testSchema, { - minMaxDateCalculated: (new Date(Date.UTC(2012, 11, 31))), - }).to.deep.equal(1); - }); - }); + minMaxDateCalculated: (new Date(Date.UTC(2012, 11, 31))) + }).to.deep.equal(1) + }) + }) describe('modifier with $setOnInsert', function () { it('string', function () { expectErrorLength(testSchema, { $setOnInsert: { - minMaxString: 'longenough', - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxString: 'longenough' + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxString: 'short', - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + minMaxString: 'short' + } + }, { modifier: true, upsert: true }).to.deep.equal(1) expectErrorLength(testSchema, { $setOnInsert: { - minMaxStringArray: ['longenough', 'longenough'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxStringArray: ['longenough', 'longenough'] + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxStringArray: ['longenough', 'short'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + minMaxStringArray: ['longenough', 'short'] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) expectErrorLength(testSchema, { $setOnInsert: { - minMaxStringArray: ['short', 'short'], - }, - }, { modifier: true, upsert: true }).to.deep.equal(2); - }); + minMaxStringArray: ['short', 'short'] + } + }, { modifier: true, upsert: true }).to.deep.equal(2) + }) it('number', function () { expectErrorLength(testSchema, { $setOnInsert: { - minMaxNumber: 10, - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxNumber: 10 + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxNumber: 9, - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + minMaxNumber: 9 + } + }, { modifier: true, upsert: true }).to.deep.equal(1) expectErrorLength(testSchema, { $setOnInsert: { - minMaxNumberCalculated: 10, - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxNumberCalculated: 10 + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxNumberCalculated: 9, - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + minMaxNumberCalculated: 9 + } + }, { modifier: true, upsert: true }).to.deep.equal(1) expectErrorLength(testSchema, { $setOnInsert: { - minZero: -1, - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); + minZero: -1 + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) it('date', function () { expectErrorLength(testSchema, { $setOnInsert: { - minMaxDate: (new Date(Date.UTC(2013, 0, 1))), - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxDate: (new Date(Date.UTC(2013, 0, 1))) + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxDate: (new Date(Date.UTC(2012, 11, 31))), - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); + minMaxDate: (new Date(Date.UTC(2012, 11, 31))) + } + }, { modifier: true, upsert: true }).to.deep.equal(1) expectErrorLength(testSchema, { $setOnInsert: { - minMaxDateCalculated: (new Date(Date.UTC(2013, 0, 1))), - }, - }, { modifier: true, upsert: true }).to.deep.equal(0); + minMaxDateCalculated: (new Date(Date.UTC(2013, 0, 1))) + } + }, { modifier: true, upsert: true }).to.deep.equal(0) expectErrorLength(testSchema, { $setOnInsert: { - minMaxDateCalculated: (new Date(Date.UTC(2012, 11, 31))), - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); - }); + minMaxDateCalculated: (new Date(Date.UTC(2012, 11, 31))) + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) + }) describe('modifier with $set or $inc', function () { it('string', function () { expectErrorLength(testSchema, { $set: { - minMaxString: 'longenough', - }, - }, { modifier: true }).to.deep.equal(0); + minMaxString: 'longenough' + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxString: 'short', - }, - }, { modifier: true }).to.deep.equal(1); + minMaxString: 'short' + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - minMaxStringArray: ['longenough', 'longenough'], - }, - }, { modifier: true }).to.deep.equal(0); + minMaxStringArray: ['longenough', 'longenough'] + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxStringArray: ['longenough', 'short'], - }, - }, { modifier: true }).to.deep.equal(1); + minMaxStringArray: ['longenough', 'short'] + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - minMaxStringArray: ['short', 'short'], - }, - }, { modifier: true }).to.deep.equal(2); - }); + minMaxStringArray: ['short', 'short'] + } + }, { modifier: true }).to.deep.equal(2) + }) it('number', function () { expectErrorLength(testSchema, { $set: { - minMaxNumber: 10, - }, - }, { modifier: true }).to.deep.equal(0); + minMaxNumber: 10 + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxNumber: 9, - }, - }, { modifier: true }).to.deep.equal(1); + minMaxNumber: 9 + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - minMaxNumberCalculated: 10, - }, - }, { modifier: true }).to.deep.equal(0); + minMaxNumberCalculated: 10 + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxNumberCalculated: 9, - }, - }, { modifier: true }).to.deep.equal(1); + minMaxNumberCalculated: 9 + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - minZero: -1, - }, - }, { modifier: true }).to.deep.equal(1); + minZero: -1 + } + }, { modifier: true }).to.deep.equal(1) // Should not be invalid because we don't know what we're starting from expectErrorLength(testSchema, { $inc: { - minZero: -5, - }, - }, { modifier: true }).to.deep.equal(0); - }); + minZero: -5 + } + }, { modifier: true }).to.deep.equal(0) + }) it('date', function () { expectErrorLength(testSchema, { $set: { - minMaxDate: (new Date(Date.UTC(2013, 0, 1))), - }, - }, { modifier: true }).to.deep.equal(0); + minMaxDate: (new Date(Date.UTC(2013, 0, 1))) + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxDate: (new Date(Date.UTC(2012, 11, 31))), - }, - }, { modifier: true }).to.deep.equal(1); + minMaxDate: (new Date(Date.UTC(2012, 11, 31))) + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(testSchema, { $set: { - minMaxDateCalculated: (new Date(Date.UTC(2013, 0, 1))), - }, - }, { modifier: true }).to.deep.equal(0); + minMaxDateCalculated: (new Date(Date.UTC(2013, 0, 1))) + } + }, { modifier: true }).to.deep.equal(0) expectErrorLength(testSchema, { $set: { - minMaxDateCalculated: (new Date(Date.UTC(2012, 11, 31))), - }, - }, { modifier: true }).to.deep.equal(1); - }); - }); -}); + minMaxDateCalculated: (new Date(Date.UTC(2012, 11, 31))) + } + }, { modifier: true }).to.deep.equal(1) + }) + }) +}) diff --git a/lib/SimpleSchema_minCount.tests.js b/lib/SimpleSchema_minCount.tests.js index 4cd582d..0c0e370 100644 --- a/lib/SimpleSchema_minCount.tests.js +++ b/lib/SimpleSchema_minCount.tests.js @@ -1,26 +1,26 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import friendsSchema from './testHelpers/friendsSchema'; -import expectErrorLength from './testHelpers/expectErrorLength'; +import friendsSchema from './testHelpers/friendsSchema' +import expectErrorLength from './testHelpers/expectErrorLength' describe('SimpleSchema - minCount', function () { it('ensures array count is at least the minimum', function () { expectErrorLength(friendsSchema, { friends: [], - enemies: [], - }).to.deep.equal(1); + enemies: [] + }).to.deep.equal(1) expectErrorLength(friendsSchema, { $set: { - friends: [], - }, - }, { modifier: true }).to.deep.equal(1); + friends: [] + } + }, { modifier: true }).to.deep.equal(1) expectErrorLength(friendsSchema, { $setOnInsert: { friends: [], - enemies: [], - }, - }, { modifier: true, upsert: true }).to.deep.equal(1); - }); -}); + enemies: [] + } + }, { modifier: true, upsert: true }).to.deep.equal(1) + }) +}) diff --git a/lib/SimpleSchema_namedContext.tests.js b/lib/SimpleSchema_namedContext.tests.js index 246864c..03fefd3 100644 --- a/lib/SimpleSchema_namedContext.tests.js +++ b/lib/SimpleSchema_namedContext.tests.js @@ -1,28 +1,28 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema - namedContext', function () { it('returns a named context', function () { - const schema = new SimpleSchema({}); - const context = schema.namedContext('form'); - expect(context.name).to.equal('form'); - expect(schema._validationContexts.form).to.equal(context); - }); + const schema = new SimpleSchema({}) + const context = schema.namedContext('form') + expect(context.name).to.equal('form') + expect(schema._validationContexts.form).to.equal(context) + }) it('returns a context named "default" if no name is passed', function () { - const schema = new SimpleSchema({}); - const context = schema.namedContext(); - expect(context.name).to.equal('default'); - expect(schema._validationContexts.default).to.equal(context); - }); + const schema = new SimpleSchema({}) + const context = schema.namedContext() + expect(context.name).to.equal('default') + expect(schema._validationContexts.default).to.equal(context) + }) it('returns the same context instance when called with the same name', function () { - const schema = new SimpleSchema({}); - const context1 = schema.namedContext('abc'); - expect(schema._validationContexts.abc).to.equal(context1); - const context2 = schema.namedContext('abc'); - expect(context2).to.equal(context1); - }); -}); + const schema = new SimpleSchema({}) + const context1 = schema.namedContext('abc') + expect(schema._validationContexts.abc).to.equal(context1) + const context2 = schema.namedContext('abc') + expect(context2).to.equal(context1) + }) +}) diff --git a/lib/SimpleSchema_omit.tests.js b/lib/SimpleSchema_omit.tests.js index 3bc9601..e53725d 100644 --- a/lib/SimpleSchema_omit.tests.js +++ b/lib/SimpleSchema_omit.tests.js @@ -1,7 +1,7 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema', function () { it('omit', function () { @@ -10,19 +10,19 @@ describe('SimpleSchema', function () { 'foo.bar': { type: String }, fooArray: { type: Array }, 'fooArray.$': { type: Object }, - 'fooArray.$.bar': { type: String }, - }); + 'fooArray.$.bar': { type: String } + }) - let newSchema = schema.omit('foo'); - expect(Object.keys(newSchema.schema())).to.deep.equal(['fooArray', 'fooArray.$', 'fooArray.$.bar']); + let newSchema = schema.omit('foo') + expect(Object.keys(newSchema.schema())).to.deep.equal(['fooArray', 'fooArray.$', 'fooArray.$.bar']) - newSchema = schema.omit('fooArray'); - expect(Object.keys(newSchema.schema())).to.deep.equal(['foo', 'foo.bar']); + newSchema = schema.omit('fooArray') + expect(Object.keys(newSchema.schema())).to.deep.equal(['foo', 'foo.bar']) - newSchema = schema.omit('foo', 'fooArray'); - expect(Object.keys(newSchema.schema())).to.deep.equal([]); + newSchema = schema.omit('foo', 'fooArray') + expect(Object.keys(newSchema.schema())).to.deep.equal([]) - newSchema = schema.omit('blah'); - expect(Object.keys(newSchema.schema())).to.deep.equal(['foo', 'foo.bar', 'fooArray', 'fooArray.$', 'fooArray.$.bar']); - }); -}); + newSchema = schema.omit('blah') + expect(Object.keys(newSchema.schema())).to.deep.equal(['foo', 'foo.bar', 'fooArray', 'fooArray.$', 'fooArray.$.bar']) + }) +}) diff --git a/lib/SimpleSchema_oneOf.tests.js b/lib/SimpleSchema_oneOf.tests.js index d663ed1..9985e27 100644 --- a/lib/SimpleSchema_oneOf.tests.js +++ b/lib/SimpleSchema_oneOf.tests.js @@ -1,186 +1,186 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema', function () { describe('oneOf', function () { it('allows either type', function () { const schema = new SimpleSchema({ - foo: SimpleSchema.oneOf(String, Number, Date), - }); + foo: SimpleSchema.oneOf(String, Number, Date) + }) - const test1 = { foo: 1 }; + const test1 = { foo: 1 } expect(function test1func () { - schema.validate(test1); - }).not.to.throw(); - expect(typeof test1.foo).to.equal('number'); + schema.validate(test1) + }).not.to.throw() + expect(typeof test1.foo).to.equal('number') - const test2 = { foo: 'bar' }; + const test2 = { foo: 'bar' } expect(function test2func () { - schema.validate(test2); - }).not.to.throw(); - expect(typeof test2.foo).to.equal('string'); + schema.validate(test2) + }).not.to.throw() + expect(typeof test2.foo).to.equal('string') - const test3 = { foo: new Date() }; + const test3 = { foo: new Date() } expect(function test2func () { - schema.validate(test3); - }).not.to.throw(); - expect(test3.foo instanceof Date).to.equal(true); + schema.validate(test3) + }).not.to.throw() + expect(test3.foo instanceof Date).to.equal(true) - const test4 = { foo: false }; + const test4 = { foo: false } expect(function test3func () { - schema.validate(test4); - }).to.throw(); - expect(typeof test4.foo).to.equal('boolean'); - }); + schema.validate(test4) + }).to.throw() + expect(typeof test4.foo).to.equal('boolean') + }) it.skip('allows either type including schemas', function () { const schemaOne = new SimpleSchema({ itemRef: String, - partNo: String, - }); + partNo: String + }) const schemaTwo = new SimpleSchema({ anotherIdentifier: String, - partNo: String, - }); + partNo: String + }) const combinedSchema = new SimpleSchema({ - item: SimpleSchema.oneOf(String, schemaOne, schemaTwo), - }); + item: SimpleSchema.oneOf(String, schemaOne, schemaTwo) + }) let isValid = combinedSchema.namedContext().validate({ - item: 'foo', - }); - expect(isValid).to.equal(true); + item: 'foo' + }) + expect(isValid).to.equal(true) isValid = combinedSchema.namedContext().validate({ item: { anotherIdentifier: 'hhh', - partNo: 'ttt', - }, - }); - expect(isValid).to.equal(true); + partNo: 'ttt' + } + }) + expect(isValid).to.equal(true) isValid = combinedSchema.namedContext().validate({ item: { itemRef: 'hhh', - partNo: 'ttt', - }, - }); - expect(isValid).to.equal(true); - }); + partNo: 'ttt' + } + }) + expect(isValid).to.equal(true) + }) it('is valid as long as one min value is met', function () { const schema = new SimpleSchema({ foo: SimpleSchema.oneOf({ type: SimpleSchema.Integer, - min: 5, + min: 5 }, { type: SimpleSchema.Integer, - min: 10, - }), - }); + min: 10 + }) + }) expect(function () { - schema.validate({ foo: 7 }); - }).not.to.throw(); - }); + schema.validate({ foo: 7 }) + }).not.to.throw() + }) it('works when one is an array', function () { const schema = new SimpleSchema({ foo: SimpleSchema.oneOf(String, Array), - 'foo.$': String, - }); + 'foo.$': String + }) expect(function () { schema.validate({ - foo: 'bar', - }); - }).not.to.throw(); + foo: 'bar' + }) + }).not.to.throw() expect(function () { schema.validate({ - foo: 1, - }); - }).to.throw(); + foo: 1 + }) + }).to.throw() expect(function () { schema.validate({ - foo: [], - }); - }).not.to.throw(); + foo: [] + }) + }).not.to.throw() expect(function () { schema.validate({ - foo: ['bar', 'bin'], - }); - }).not.to.throw(); + foo: ['bar', 'bin'] + }) + }).not.to.throw() expect(function () { schema.validate({ - foo: ['bar', 1], - }); - }).to.throw(); - }); + foo: ['bar', 1] + }) + }).to.throw() + }) it('works when one is a schema', function () { const objSchema = new SimpleSchema({ - _id: String, - }); + _id: String + }) const schema = new SimpleSchema({ - foo: SimpleSchema.oneOf(String, objSchema), - }); + foo: SimpleSchema.oneOf(String, objSchema) + }) expect(function () { schema.validate({ - foo: 'bar', - }); - }).not.to.throw(); + foo: 'bar' + }) + }).not.to.throw() expect(function () { schema.validate({ - foo: 1, - }); - }).to.throw(); + foo: 1 + }) + }).to.throw() expect(function () { schema.validate({ - foo: [], - }); - }).to.throw(); + foo: [] + }) + }).to.throw() expect(function () { schema.validate({ - foo: {}, - }); - }).to.throw(); + foo: {} + }) + }).to.throw() expect(function () { schema.validate({ foo: { - _id: 'ID', - }, - }); - }).not.to.throw(); - }); + _id: 'ID' + } + }) + }).not.to.throw() + }) it('is invalid if neither min value is met', function () { const schema = new SimpleSchema({ foo: SimpleSchema.oneOf({ type: SimpleSchema.Integer, - min: 5, + min: 5 }, { type: SimpleSchema.Integer, - min: 10, - }), - }); + min: 10 + }) + }) expect(function () { - schema.validate({ foo: 3 }); - }).to.throw(); - }); - }); -}); + schema.validate({ foo: 3 }) + }).to.throw() + }) + }) +}) diff --git a/lib/SimpleSchema_pick.tests.js b/lib/SimpleSchema_pick.tests.js index c749047..1a11548 100644 --- a/lib/SimpleSchema_pick.tests.js +++ b/lib/SimpleSchema_pick.tests.js @@ -1,7 +1,7 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema', function () { it('pick', function () { @@ -10,30 +10,30 @@ describe('SimpleSchema', function () { 'foo.bar': { type: String }, fooArray: { type: Array }, 'fooArray.$': { type: Object }, - 'fooArray.$.bar': { type: String }, - }); + 'fooArray.$.bar': { type: String } + }) - let newSchema = schema.pick('foo'); - expect(Object.keys(newSchema.schema())).to.deep.equal(['foo', 'foo.bar']); + let newSchema = schema.pick('foo') + expect(Object.keys(newSchema.schema())).to.deep.equal(['foo', 'foo.bar']) - newSchema = schema.pick('fooArray'); - expect(Object.keys(newSchema.schema())).to.deep.equal(['fooArray', 'fooArray.$', 'fooArray.$.bar']); + newSchema = schema.pick('fooArray') + expect(Object.keys(newSchema.schema())).to.deep.equal(['fooArray', 'fooArray.$', 'fooArray.$.bar']) - newSchema = schema.pick('foo', 'fooArray'); - expect(Object.keys(newSchema.schema())).to.deep.equal(['foo', 'foo.bar', 'fooArray', 'fooArray.$', 'fooArray.$.bar']); + newSchema = schema.pick('foo', 'fooArray') + expect(Object.keys(newSchema.schema())).to.deep.equal(['foo', 'foo.bar', 'fooArray', 'fooArray.$', 'fooArray.$.bar']) - newSchema = schema.pick('blah'); - expect(Object.keys(newSchema.schema())).to.deep.equal([]); - }); + newSchema = schema.pick('blah') + expect(Object.keys(newSchema.schema())).to.deep.equal([]) + }) it('error when you do not pick the parent', () => { const schema = new SimpleSchema({ level1: { type: Object }, - 'level1.level2': { type: Boolean }, - }); + 'level1.level2': { type: Boolean } + }) expect(() => { - schema.pick('level1.level2'); - }).to.throw('"level1.level2" is in the schema but "level1" is not'); - }); -}); + schema.pick('level1.level2') + }).to.throw('"level1.level2" is in the schema but "level1" is not') + }) +}) diff --git a/lib/SimpleSchema_regEx.tests.js b/lib/SimpleSchema_regEx.tests.js index a6f4ce7..8484ca0 100644 --- a/lib/SimpleSchema_regEx.tests.js +++ b/lib/SimpleSchema_regEx.tests.js @@ -1,7 +1,7 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema', function () { it('regEx - issue 409', function () { @@ -10,14 +10,14 @@ describe('SimpleSchema', function () { foo: { type: String, optional: true, - regEx: /bar/, - }, - }); + regEx: /bar/ + } + }) - expect(schema.newContext().validate({})).to.deep.equal(true); - expect(schema.newContext().validate({ foo: null })).to.deep.equal(true); - expect(schema.newContext().validate({ foo: '' })).to.deep.equal(false); - }); + expect(schema.newContext().validate({})).to.deep.equal(true) + expect(schema.newContext().validate({ foo: null })).to.deep.equal(true) + expect(schema.newContext().validate({ foo: '' })).to.deep.equal(false) + }) it('no regEx errors for empty strings when `skipRegExCheckForEmptyStrings` field option is true', function () { const schema = new SimpleSchema({ @@ -25,398 +25,398 @@ describe('SimpleSchema', function () { type: String, optional: true, regEx: /bar/, - skipRegExCheckForEmptyStrings: true, - }, - }); + skipRegExCheckForEmptyStrings: true + } + }) - expect(schema.newContext().validate({ foo: '' })).to.equal(true); + expect(schema.newContext().validate({ foo: '' })).to.equal(true) // still fails when not empty string, though - expect(schema.newContext().validate({ foo: 'bad' })).to.equal(false); - }); + expect(schema.newContext().validate({ foo: 'bad' })).to.equal(false) + }) it('Built-In RegEx and Messages', function () { const schema = new SimpleSchema({ email: { type: String, regEx: SimpleSchema.RegEx.Email, - optional: true, + optional: true }, emailWithTLD: { type: String, regEx: SimpleSchema.RegEx.EmailWithTLD, - optional: true, + optional: true }, domain: { type: String, regEx: SimpleSchema.RegEx.Domain, - optional: true, + optional: true }, weakDomain: { type: String, regEx: SimpleSchema.RegEx.WeakDomain, - optional: true, + optional: true }, ip: { type: String, regEx: SimpleSchema.RegEx.IP, - optional: true, + optional: true }, ip4: { type: String, regEx: SimpleSchema.RegEx.IPv4, - optional: true, + optional: true }, ip6: { type: String, regEx: SimpleSchema.RegEx.IPv6, - optional: true, + optional: true }, url: { type: String, regEx: SimpleSchema.RegEx.Url, - optional: true, + optional: true }, id: { type: String, regEx: SimpleSchema.RegEx.Id, - optional: true, + optional: true }, longId: { type: String, regEx: SimpleSchema.RegEx.idOfLength(32), - optional: true, - }, - }); + optional: true + } + }) - const c1 = schema.newContext(); + const c1 = schema.newContext() c1.validate({ - email: 'foo', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('email')).to.deep.equal('Email must be a valid email address'); + email: 'foo' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('email')).to.deep.equal('Email must be a valid email address') c1.validate({ - emailWithTLD: 'foo', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('emailWithTLD')).to.deep.equal('Email with tld must be a valid email address'); + emailWithTLD: 'foo' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('emailWithTLD')).to.deep.equal('Email with tld must be a valid email address') c1.validate({ - domain: 'foo', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('domain')).to.deep.equal('Domain must be a valid domain'); + domain: 'foo' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('domain')).to.deep.equal('Domain must be a valid domain') c1.validate({ - weakDomain: '///jioh779&%', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('weakDomain')).to.deep.equal('Weak domain must be a valid domain'); + weakDomain: '///jioh779&%' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('weakDomain')).to.deep.equal('Weak domain must be a valid domain') c1.validate({ - ip: 'foo', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('ip')).to.deep.equal('Ip must be a valid IPv4 or IPv6 address'); + ip: 'foo' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('ip')).to.deep.equal('Ip must be a valid IPv4 or IPv6 address') c1.validate({ - ip4: 'foo', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('ip4')).to.deep.equal('Ip4 must be a valid IPv4 address'); + ip4: 'foo' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('ip4')).to.deep.equal('Ip4 must be a valid IPv4 address') c1.validate({ - ip6: 'foo', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('ip6')).to.deep.equal('Ip6 must be a valid IPv6 address'); + ip6: 'foo' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('ip6')).to.deep.equal('Ip6 must be a valid IPv6 address') c1.validate({ - url: 'foo', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('url')).to.deep.equal('Url must be a valid URL'); + url: 'foo' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('url')).to.deep.equal('Url must be a valid URL') c1.validate({ - id: '%#$%', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('id')).to.deep.equal('ID must be a valid alphanumeric ID'); + id: '%#$%' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('id')).to.deep.equal('ID must be a valid alphanumeric ID') c1.validate({ - longId: '%#$%', - }); - expect(c1.validationErrors().length).to.deep.equal(1); - expect(c1.keyErrorMessage('longId')).to.deep.equal('Long ID failed regular expression validation'); - }); + longId: '%#$%' + }) + expect(c1.validationErrors().length).to.deep.equal(1) + expect(c1.keyErrorMessage('longId')).to.deep.equal('Long ID failed regular expression validation') + }) it('Optional regEx in subobject', function () { const schema = new SimpleSchema({ foo: { type: Object, - optional: true, + optional: true }, 'foo.url': { type: String, regEx: SimpleSchema.RegEx.Url, - optional: true, - }, - }); + optional: true + } + }) - const context = schema.namedContext(); + const context = schema.namedContext() - expect(context.validate({})).to.deep.equal(true); + expect(context.validate({})).to.deep.equal(true) expect(context.validate({ - foo: {}, - })).to.deep.equal(true); + foo: {} + })).to.deep.equal(true) expect(context.validate({ foo: { - url: null, - }, - })).to.deep.equal(true); + url: null + } + })).to.deep.equal(true) expect(context.validate({ $set: { - foo: {}, - }, - }, { modifier: true })).to.deep.equal(true); + foo: {} + } + }, { modifier: true })).to.deep.equal(true) expect(context.validate({ $set: { - 'foo.url': null, - }, - }, { modifier: true })).to.deep.equal(true); + 'foo.url': null + } + }, { modifier: true })).to.deep.equal(true) expect(context.validate({ $unset: { - 'foo.url': '', - }, - }, { modifier: true })).to.deep.equal(true); - }); + 'foo.url': '' + } + }, { modifier: true })).to.deep.equal(true) + }) it('SimpleSchema.RegEx.Email', function () { - const expr = SimpleSchema.RegEx.Email; + const expr = SimpleSchema.RegEx.Email - function isTrue(s) { - expect(expr.test(s)).to.equal(true); + function isTrue (s) { + expect(expr.test(s)).to.equal(true) } - function isFalse(s) { - expect(expr.test(s)).to.equal(false); + function isFalse (s) { + expect(expr.test(s)).to.equal(false) } - isTrue('name@web.de'); - isTrue('name+addition@web.de'); - isTrue('st#r~ange.e+mail@web.de'); - isTrue('name@localhost'); - isTrue('name@192.168.200.5'); - isFalse('name@BCDF:45AB:1245:75B9:0987:1562:4567:1234'); - isFalse('name@BCDF:45AB:1245:75B9::0987:1234:1324'); - isFalse('name@BCDF:45AB:1245:75B9:0987:1234:1324'); - isFalse('name@::1'); - }); + isTrue('name@web.de') + isTrue('name+addition@web.de') + isTrue('st#r~ange.e+mail@web.de') + isTrue('name@localhost') + isTrue('name@192.168.200.5') + isFalse('name@BCDF:45AB:1245:75B9:0987:1562:4567:1234') + isFalse('name@BCDF:45AB:1245:75B9::0987:1234:1324') + isFalse('name@BCDF:45AB:1245:75B9:0987:1234:1324') + isFalse('name@::1') + }) it('SimpleSchema.RegEx.EmailWithTLD', function () { - const expr = SimpleSchema.RegEx.EmailWithTLD; + const expr = SimpleSchema.RegEx.EmailWithTLD - function isTrue(s) { - expect(expr.test(s)).to.equal(true); + function isTrue (s) { + expect(expr.test(s)).to.equal(true) } - function isFalse(s) { - expect(expr.test(s)).to.equal(false); + function isFalse (s) { + expect(expr.test(s)).to.equal(false) } - isTrue('name@web.de'); - isTrue('name+addition@web.de'); - isTrue('st#r~ange.e+mail@web.de'); - isFalse('name@localhost'); - isFalse('name@192.168.200.5'); - isFalse('name@BCDF:45AB:1245:75B9:0987:1562:4567:1234'); - isFalse('name@BCDF:45AB:1245:75B9::0987:1234:1324'); - isFalse('name@BCDF:45AB:1245:75B9:0987:1234:1324'); - isFalse('name@::1'); - }); + isTrue('name@web.de') + isTrue('name+addition@web.de') + isTrue('st#r~ange.e+mail@web.de') + isFalse('name@localhost') + isFalse('name@192.168.200.5') + isFalse('name@BCDF:45AB:1245:75B9:0987:1562:4567:1234') + isFalse('name@BCDF:45AB:1245:75B9::0987:1234:1324') + isFalse('name@BCDF:45AB:1245:75B9:0987:1234:1324') + isFalse('name@::1') + }) it('SimpleSchema.RegEx.Domain', function () { - const expr = SimpleSchema.RegEx.Domain; + const expr = SimpleSchema.RegEx.Domain - function isTrue(s) { - expect(expr.test(s)).to.equal(true); + function isTrue (s) { + expect(expr.test(s)).to.equal(true) } - function isFalse(s) { - expect(expr.test(s)).to.equal(false); + function isFalse (s) { + expect(expr.test(s)).to.equal(false) } - isTrue('domain.com'); - isFalse('localhost'); - isFalse('192.168.200.5'); - isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234:AB36'); - }); + isTrue('domain.com') + isFalse('localhost') + isFalse('192.168.200.5') + isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234:AB36') + }) it('SimpleSchema.RegEx.WeakDomain', function () { - const expr = SimpleSchema.RegEx.WeakDomain; + const expr = SimpleSchema.RegEx.WeakDomain - function isTrue(s) { - expect(expr.test(s)).to.equal(true); + function isTrue (s) { + expect(expr.test(s)).to.equal(true) } - isTrue('domain.com'); - isTrue('localhost'); - isTrue('192.168.200.5'); - isTrue('BCDF:45AB:1245:75B9:0987:1562:4567:1234'); - }); + isTrue('domain.com') + isTrue('localhost') + isTrue('192.168.200.5') + isTrue('BCDF:45AB:1245:75B9:0987:1562:4567:1234') + }) it('SimpleSchema.RegEx.IP', function () { - const expr = SimpleSchema.RegEx.IP; + const expr = SimpleSchema.RegEx.IP - function isTrue(s) { - expect(expr.test(s)).to.equal(true); + function isTrue (s) { + expect(expr.test(s)).to.equal(true) } - function isFalse(s) { - expect(expr.test(s)).to.equal(false); + function isFalse (s) { + expect(expr.test(s)).to.equal(false) } - isFalse('localhost'); - isTrue('192.168.200.5'); - isFalse('320.168.200.5'); - isFalse('192.168.5'); - isTrue('BCDF:45AB:1245:75B9:0987:1562:4567:1234'); - isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234:AB36'); - isTrue('BCDF:45AB:1245:75B9::0987:1234:1324'); - isFalse('BCDF:45AB:1245:75B9:0987:1234:1324'); - isTrue('::1'); - }); + isFalse('localhost') + isTrue('192.168.200.5') + isFalse('320.168.200.5') + isFalse('192.168.5') + isTrue('BCDF:45AB:1245:75B9:0987:1562:4567:1234') + isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234:AB36') + isTrue('BCDF:45AB:1245:75B9::0987:1234:1324') + isFalse('BCDF:45AB:1245:75B9:0987:1234:1324') + isTrue('::1') + }) it('SimpleSchema.RegEx.IPv4', function () { - const expr = SimpleSchema.RegEx.IPv4; + const expr = SimpleSchema.RegEx.IPv4 - function isTrue(s) { - expect(expr.test(s)).to.equal(true); + function isTrue (s) { + expect(expr.test(s)).to.equal(true) } - function isFalse(s) { - expect(expr.test(s)).to.equal(false); + function isFalse (s) { + expect(expr.test(s)).to.equal(false) } - isFalse('localhost'); - isTrue('192.168.200.5'); - isFalse('320.168.200.5'); - isFalse('192.168.5'); - isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234'); - isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234:AB36'); - isFalse('BCDF:45AB:1245:75B9::0987:1234:1324'); - isFalse('BCDF:45AB:1245:75B9:0987:1234:1324'); - isFalse('::1'); - }); + isFalse('localhost') + isTrue('192.168.200.5') + isFalse('320.168.200.5') + isFalse('192.168.5') + isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234') + isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234:AB36') + isFalse('BCDF:45AB:1245:75B9::0987:1234:1324') + isFalse('BCDF:45AB:1245:75B9:0987:1234:1324') + isFalse('::1') + }) it('SimpleSchema.RegEx.IPv6', function () { - const expr = SimpleSchema.RegEx.IPv6; + const expr = SimpleSchema.RegEx.IPv6 - function isTrue(s) { - expect(expr.test(s)).to.equal(true); + function isTrue (s) { + expect(expr.test(s)).to.equal(true) } - function isFalse(s) { - expect(expr.test(s)).to.equal(false); + function isFalse (s) { + expect(expr.test(s)).to.equal(false) } - isFalse('localhost'); - isFalse('192.168.200.5'); - isFalse('320.168.200.5'); - isFalse('192.168.5'); - isTrue('BCDF:45AB:1245:75B9:0987:1562:4567:1234'); - isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234:AB36'); - isTrue('BCDF:45AB:1245:75B9::0987:1234:1324'); - isFalse('BCDF:45AB:1245:75B9:0987:1234:1324'); - isTrue('::1'); - }); + isFalse('localhost') + isFalse('192.168.200.5') + isFalse('320.168.200.5') + isFalse('192.168.5') + isTrue('BCDF:45AB:1245:75B9:0987:1562:4567:1234') + isFalse('BCDF:45AB:1245:75B9:0987:1562:4567:1234:AB36') + isTrue('BCDF:45AB:1245:75B9::0987:1234:1324') + isFalse('BCDF:45AB:1245:75B9:0987:1234:1324') + isTrue('::1') + }) // this is a simple fake-random id generator that generates the // ids with numbers that are expected to be valid for the Id and IdOf regexp const Random = { UNMISTAKABLE_CHARS: '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz', id (charsCount = 17) { - let id = ''; - const len = Random.UNMISTAKABLE_CHARS.length; + let id = '' + const len = Random.UNMISTAKABLE_CHARS.length for (let i = 0; i < charsCount; i++) { - const index = Math.floor(Math.random() * len); - id += Random.UNMISTAKABLE_CHARS[index]; + const index = Math.floor(Math.random() * len) + id += Random.UNMISTAKABLE_CHARS[index] } - return id; - }, - }; + return id + } + } it('SimpleSchema.RegEx.Id', function () { - const idExpr = SimpleSchema.RegEx.Id; - const isTrue = (s) => expect(idExpr.test(s)).to.equal(true); - const isFalse = (s) => expect(idExpr.test(s)).to.equal(false); + const idExpr = SimpleSchema.RegEx.Id + const isTrue = (s) => expect(idExpr.test(s)).to.equal(true) + const isFalse = (s) => expect(idExpr.test(s)).to.equal(false) - isTrue(Random.id()); - isFalse(Random.id(16)); // less - isFalse(Random.id(18)); // greater - isFalse('01234567891011123'); // invalid chars - }); + isTrue(Random.id()) + isFalse(Random.id(16)) // less + isFalse(Random.id(18)) // greater + isFalse('01234567891011123') // invalid chars + }) it('SimpleSchema.RegEx.idOfLength', function () { - const { idOfLength } = SimpleSchema.RegEx; - const expectThrows = (min, max) => expect(() => idOfLength(min, max)).to.throw(/Expected a non-negative safe integer/); + const { idOfLength } = SimpleSchema.RegEx + const expectThrows = (min, max) => expect(() => idOfLength(min, max)).to.throw(/Expected a non-negative safe integer/) // lets add some fuzzing to see if there are some unexpected edge cases // when generating the id RegExp pattern using SimpleSchema.RegEx.IdOf - const randomMinValues = (fn, times) => (new Array(times)).forEach(() => expectThrows(fn())); - const randomMaxValues = (min, fn, times) => (new Array(times)).forEach(() => expectThrows(min, fn())); + const randomMinValues = (fn, times) => (new Array(times)).forEach(() => expectThrows(fn())) + const randomMaxValues = (min, fn, times) => (new Array(times)).forEach(() => expectThrows(min, fn())) // unexpected min values // no negatives - randomMinValues(() => -1 * Math.floor(Math.random() * 100), 100); + randomMinValues(() => -1 * Math.floor(Math.random() * 100), 100) // no floating point numbers - randomMinValues(() => Math.random(), 100); + randomMinValues(() => Math.random(), 100) // only Number.MAX_SAFE_INTEGER - expectThrows(9007199254740992); + expectThrows(9007199254740992) // unexpected max values // not less than min - expectThrows(10, 9); + expectThrows(10, 9) // no negatives - randomMaxValues(10, () => -1 * Math.floor(Math.random() * 100), 100); + randomMaxValues(10, () => -1 * Math.floor(Math.random() * 100), 100) // no negatives - randomMaxValues(10, () => -1 * Math.floor(Math.random() * 100), 100); + randomMaxValues(10, () => -1 * Math.floor(Math.random() * 100), 100) // no floating point numbers - randomMaxValues(10, () => Math.random(), 100); + randomMaxValues(10, () => Math.random(), 100) // only Number.MAX_SAFE_INTEGER - expectThrows(10, 9007199254740992); + expectThrows(10, 9007199254740992) - const isTrue = (expr, s) => expect(expr.test(s)).to.equal(true); - const isFalse = (expr, s) => expect(expr.test(s)).to.equal(false); + const isTrue = (expr, s) => expect(expr.test(s)).to.equal(true) + const isFalse = (expr, s) => expect(expr.test(s)).to.equal(false) // arbitrary length ids - const anyLen = idOfLength(0, null); + const anyLen = idOfLength(0, null) for (let i = 1; i < 100; i++) { - isTrue(anyLen, Random.id(i)); + isTrue(anyLen, Random.id(i)) } // fixed length ids - isTrue(idOfLength(17), Random.id()); - isTrue(idOfLength(32), Random.id(32)); - isFalse(idOfLength(16), Random.id()); // greater - isFalse(idOfLength(32), Random.id()); // less + isTrue(idOfLength(17), Random.id()) + isTrue(idOfLength(32), Random.id(32)) + isFalse(idOfLength(16), Random.id()) // greater + isFalse(idOfLength(32), Random.id()) // less // range of length ids with fixed upper bound - isTrue(idOfLength(8, 128), '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz'); - isFalse(idOfLength(8, 128), '1234567890abcdefghijklmnopqrstuvwxyz'); // invalid chars - isFalse(idOfLength(8, 128), '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz%$/(='); // invalid chars 2 + isTrue(idOfLength(8, 128), '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz') + isFalse(idOfLength(8, 128), '1234567890abcdefghijklmnopqrstuvwxyz') // invalid chars + isFalse(idOfLength(8, 128), '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz%$/(=') // invalid chars 2 // range of length ids with arbitrary upper bound - isTrue(idOfLength(8, null), '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz'); - isFalse(idOfLength(8, null), '1234567890abcdefghijklmnopqrstuvwxyz'); // invalid chars - isFalse(idOfLength(8, null), '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz%$/(='); // invalid chars 2 - }); -}); + isTrue(idOfLength(8, null), '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz') + isFalse(idOfLength(8, null), '1234567890abcdefghijklmnopqrstuvwxyz') // invalid chars + isFalse(idOfLength(8, null), '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz%$/(=') // invalid chars 2 + }) +}) diff --git a/lib/SimpleSchema_required.tests.js b/lib/SimpleSchema_required.tests.js index e5cd73e..ca86333 100644 --- a/lib/SimpleSchema_required.tests.js +++ b/lib/SimpleSchema_required.tests.js @@ -1,12 +1,12 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { SimpleSchema } from './SimpleSchema'; -import requiredSchema from './testHelpers/requiredSchema'; -import testSchema from './testHelpers/testSchema'; -import friendsSchema from './testHelpers/friendsSchema'; -import expectValid from './testHelpers/expectValid'; -import expectErrorLength from './testHelpers/expectErrorLength'; -import expectRequiredErrorLength from './testHelpers/expectRequiredErrorLength'; +import { SimpleSchema } from './SimpleSchema' +import requiredSchema from './testHelpers/requiredSchema' +import testSchema from './testHelpers/testSchema' +import friendsSchema from './testHelpers/friendsSchema' +import expectValid from './testHelpers/expectValid' +import expectErrorLength from './testHelpers/expectErrorLength' +import expectRequiredErrorLength from './testHelpers/expectRequiredErrorLength' describe('SimpleSchema - required', function () { describe('normal', function () { @@ -19,12 +19,12 @@ describe('SimpleSchema - required', function () { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, + requiredNumber: 1 }, optionalObject: { - requiredString: 'test', - }, - }); + requiredString: 'test' + } + }) expectValid(requiredSchema, { requiredString: 'test', @@ -34,13 +34,13 @@ describe('SimpleSchema - required', function () { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, - }, - }); - }); + requiredNumber: 1 + } + }) + }) it('invalid', function () { - expectRequiredErrorLength(requiredSchema, {}).to.equal(8); + expectRequiredErrorLength(requiredSchema, {}).to.equal(8) expectRequiredErrorLength(requiredSchema, { requiredString: null, @@ -51,9 +51,9 @@ describe('SimpleSchema - required', function () { requiredUrl: null, requiredObject: null, optionalObject: { - requiredString: null, - }, - }).to.equal(9); + requiredString: null + } + }).to.equal(9) expectRequiredErrorLength(requiredSchema, { requiredString: null, @@ -63,8 +63,8 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - optionalObject: {}, - }).to.equal(9); + optionalObject: {} + }).to.equal(9) // we should not get an error about optionalObject.requiredString because the whole object is null expectRequiredErrorLength(requiredSchema, { @@ -75,8 +75,8 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - optionalObject: null, - }).to.equal(8); + optionalObject: null + }).to.equal(8) // we should not get an error about optionalObject.requiredString because the whole object is missing expectRequiredErrorLength(requiredSchema, { @@ -86,8 +86,8 @@ describe('SimpleSchema - required', function () { requiredDate: null, requiredEmail: null, requiredUrl: null, - requiredObject: null, - }).to.equal(8); + requiredObject: null + }).to.equal(8) expectRequiredErrorLength(requiredSchema, { requiredString: undefined, @@ -98,9 +98,9 @@ describe('SimpleSchema - required', function () { requiredUrl: undefined, requiredObject: undefined, optionalObject: { - requiredString: undefined, - }, - }).to.equal(9); + requiredString: undefined + } + }).to.equal(9) expectRequiredErrorLength(requiredSchema, { requiredString: '', @@ -111,9 +111,9 @@ describe('SimpleSchema - required', function () { requiredUrl: null, requiredObject: null, optionalObject: { - requiredString: '', - }, - }).to.equal(7); + requiredString: '' + } + }).to.equal(7) expectRequiredErrorLength(requiredSchema, { requiredString: ' ', @@ -124,40 +124,40 @@ describe('SimpleSchema - required', function () { requiredUrl: null, requiredObject: null, optionalObject: { - requiredString: ' ', - }, - }).to.equal(7); + requiredString: ' ' + } + }).to.equal(7) // Array of objects expectRequiredErrorLength(friendsSchema, { friends: [{ - name: 'Bob', + name: 'Bob' }], - enemies: [{}], - }).to.equal(2); - }); - }); + enemies: [{}] + }).to.equal(2) + }) + }) describe('requiredByDefault', function () { it('requiredByDefault=false', function () { - const schema = new SimpleSchema({ foo: String }, { requiredByDefault: false }); - expectRequiredErrorLength(schema, {}).to.equal(0); - }); + const schema = new SimpleSchema({ foo: String }, { requiredByDefault: false }) + expectRequiredErrorLength(schema, {}).to.equal(0) + }) it('requiredByDefault=false + required=true', function () { const schema = new SimpleSchema({ - foo: { type: String, required: true }, - }, { requiredByDefault: false }); - expectRequiredErrorLength(schema, {}).to.equal(1); - }); + foo: { type: String, required: true } + }, { requiredByDefault: false }) + expectRequiredErrorLength(schema, {}).to.equal(1) + }) it('requiredByDefault=false + required()=true', function () { const schema = new SimpleSchema({ - foo: { type: String, required: () => true }, - }, { requiredByDefault: false }); - expectRequiredErrorLength(schema, {}).to.equal(1); - }); - }); + foo: { type: String, required: () => true } + }, { requiredByDefault: false }) + expectRequiredErrorLength(schema, {}).to.equal(1) + }) + }) describe('modifier with $set', function () { it('valid upsert', function () { @@ -170,13 +170,13 @@ describe('SimpleSchema - required', function () { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, + requiredNumber: 1 }, optionalObject: { - requiredString: 'test', - }, - }, - }, { modifier: true, upsert: true }); + requiredString: 'test' + } + } + }, { modifier: true, upsert: true }) expectValid(requiredSchema, { $set: { @@ -187,29 +187,29 @@ describe('SimpleSchema - required', function () { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, + requiredNumber: 1 }, - 'optionalObject.requiredString': 'test', - }, - }, { modifier: true, upsert: true }); + 'optionalObject.requiredString': 'test' + } + }, { modifier: true, upsert: true }) const schema = new SimpleSchema({ name: { type: String }, embed: { type: Object }, - 'embed._id': { type: String }, - }); + 'embed._id': { type: String } + }) expectValid(schema, { $set: { - name: 'name', - }, - }, { modifier: true }); - }); + name: 'name' + } + }, { modifier: true }) + }) it('invalid upsert', function () { expectRequiredErrorLength(requiredSchema, { - $set: {}, - }, { modifier: true, upsert: true }).to.equal(8); + $set: {} + }, { modifier: true, upsert: true }).to.equal(8) // should be no different with some missing expectRequiredErrorLength(requiredSchema, { @@ -217,9 +217,9 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': null, - }, - }, { modifier: true, upsert: true }).to.equal(9); + 'optionalObject.requiredString': null + } + }, { modifier: true, upsert: true }).to.equal(9) expectRequiredErrorLength(requiredSchema, { $set: { @@ -230,9 +230,9 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': null, - }, - }, { modifier: true, upsert: true }).to.equal(9); + 'optionalObject.requiredString': null + } + }, { modifier: true, upsert: true }).to.equal(9) expectRequiredErrorLength(requiredSchema, { $set: { @@ -243,9 +243,9 @@ describe('SimpleSchema - required', function () { requiredEmail: undefined, requiredUrl: undefined, requiredObject: undefined, - 'optionalObject.requiredString': undefined, - }, - }, { modifier: true, upsert: true }).to.equal(9); + 'optionalObject.requiredString': undefined + } + }, { modifier: true, upsert: true }).to.equal(9) expectRequiredErrorLength(requiredSchema, { $set: { @@ -256,9 +256,9 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': '', - }, - }, { modifier: true, upsert: true }).to.equal(7); + 'optionalObject.requiredString': '' + } + }, { modifier: true, upsert: true }).to.equal(7) expectRequiredErrorLength(requiredSchema, { $set: { @@ -269,16 +269,16 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': ' ', - }, - }, { modifier: true, upsert: true }).to.equal(7); - }); + 'optionalObject.requiredString': ' ' + } + }, { modifier: true, upsert: true }).to.equal(7) + }) it('valid update', function () { // Would not cause DB changes, so should not be an error expectValid(requiredSchema, { - $set: {}, - }, { modifier: true }); + $set: {} + }, { modifier: true }) expectValid(requiredSchema, { $set: { @@ -289,9 +289,9 @@ describe('SimpleSchema - required', function () { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', 'requiredObject.requiredNumber': 1, - 'optionalObject.requiredString': 'test', - }, - }, { modifier: true }); + 'optionalObject.requiredString': 'test' + } + }, { modifier: true }) expectValid(requiredSchema, { $set: { @@ -302,45 +302,45 @@ describe('SimpleSchema - required', function () { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, + requiredNumber: 1 }, - 'optionalObject.requiredString': 'test', - }, - }, { modifier: true }); + 'optionalObject.requiredString': 'test' + } + }, { modifier: true }) // Array of objects expectValid(friendsSchema, { $set: { enemies: [{ - name: 'Zach', - }], - }, - }, { modifier: true }); + name: 'Zach' + }] + } + }, { modifier: true }) expectValid(friendsSchema, { $set: { - 'friends.1.name': 'Bob', - }, - }, { modifier: true }); + 'friends.1.name': 'Bob' + } + }, { modifier: true }) expectValid(friendsSchema, { $set: { friends: [{ name: 'Bob', - type: 'good', - }], - }, - }, { modifier: true }); + type: 'good' + }] + } + }, { modifier: true }) expectValid(friendsSchema, { $set: { enemies: [{ name: 'Zach', - traits: [], - }], - }, - }, { modifier: true }); - }); + traits: [] + }] + } + }, { modifier: true }) + }) it('invalid update', function () { // MongoDB will set the props to `undefined` @@ -353,9 +353,9 @@ describe('SimpleSchema - required', function () { requiredEmail: undefined, requiredUrl: undefined, requiredObject: undefined, - 'optionalObject.requiredString': undefined, - }, - }, { modifier: true }).to.equal(9); + 'optionalObject.requiredString': undefined + } + }, { modifier: true }).to.equal(9) expectRequiredErrorLength(requiredSchema, { $set: { @@ -366,9 +366,9 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': null, - }, - }, { modifier: true }).to.equal(9); + 'optionalObject.requiredString': null + } + }, { modifier: true }).to.equal(9) expectRequiredErrorLength(requiredSchema, { $set: { @@ -379,9 +379,9 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': '', - }, - }, { modifier: true }).to.equal(7); + 'optionalObject.requiredString': '' + } + }, { modifier: true }).to.equal(7) expectRequiredErrorLength(requiredSchema, { $set: { @@ -392,63 +392,63 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': ' ', - }, - }, { modifier: true }).to.equal(7); + 'optionalObject.requiredString': ' ' + } + }, { modifier: true }).to.equal(7) // Array of objects expectRequiredErrorLength(friendsSchema, { $set: { - enemies: [{}], - }, - }, { modifier: true }).to.equal(1); + enemies: [{}] + } + }, { modifier: true }).to.equal(1) // name is required expectRequiredErrorLength(friendsSchema, { $set: { - 'friends.1.name': null, - }, - }, { modifier: true }).to.equal(1); + 'friends.1.name': null + } + }, { modifier: true }).to.equal(1) // type is required expectRequiredErrorLength(friendsSchema, { $set: { friends: [{ - name: 'Bob', - }], - }, - }, { modifier: true }).to.equal(1); + name: 'Bob' + }] + } + }, { modifier: true }).to.equal(1) expectRequiredErrorLength(friendsSchema, { $set: { enemies: [{ name: 'Zach', - traits: [{}], - }], - }, - }, { modifier: true }).to.equal(2); + traits: [{}] + }] + } + }, { modifier: true }).to.equal(2) expectRequiredErrorLength(friendsSchema, { $set: { enemies: [{ name: 'Zach', - traits: [{}, {}], - }], - }, - }, { modifier: true }).to.equal(4); + traits: [{}, {}] + }] + } + }, { modifier: true }).to.equal(4) expectRequiredErrorLength(friendsSchema, { $set: { enemies: [{ name: 'Zach', traits: [{ - name: 'evil', - }], - }], - }, - }, { modifier: true }).to.equal(1); - }); - }); + name: 'evil' + }] + }] + } + }, { modifier: true }).to.equal(1) + }) + }) describe('modifier with $setOnInsert', function () { it('valid upsert', function () { @@ -461,13 +461,13 @@ describe('SimpleSchema - required', function () { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, + requiredNumber: 1 }, optionalObject: { - requiredString: 'test', - }, - }, - }, { modifier: true, upsert: true }); + requiredString: 'test' + } + } + }, { modifier: true, upsert: true }) expectValid(requiredSchema, { $setOnInsert: { @@ -478,17 +478,17 @@ describe('SimpleSchema - required', function () { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, + requiredNumber: 1 }, - 'optionalObject.requiredString': 'test', - }, - }, { modifier: true, upsert: true }); - }); + 'optionalObject.requiredString': 'test' + } + }, { modifier: true, upsert: true }) + }) it('invalid upsert', function () { expectRequiredErrorLength(requiredSchema, { - $setOnInsert: {}, - }, { modifier: true, upsert: true }).to.equal(8); + $setOnInsert: {} + }, { modifier: true, upsert: true }).to.equal(8) expectRequiredErrorLength(requiredSchema, { $setOnInsert: { @@ -499,9 +499,9 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': null, - }, - }, { modifier: true, upsert: true }).to.equal(9); + 'optionalObject.requiredString': null + } + }, { modifier: true, upsert: true }).to.equal(9) expectRequiredErrorLength(requiredSchema, { $setOnInsert: { @@ -512,9 +512,9 @@ describe('SimpleSchema - required', function () { requiredEmail: undefined, requiredUrl: undefined, requiredObject: undefined, - 'optionalObject.requiredString': undefined, - }, - }, { modifier: true, upsert: true }).to.equal(9); + 'optionalObject.requiredString': undefined + } + }, { modifier: true, upsert: true }).to.equal(9) expectRequiredErrorLength(requiredSchema, { $setOnInsert: { @@ -525,9 +525,9 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': '', - }, - }, { modifier: true, upsert: true }).to.equal(7); + 'optionalObject.requiredString': '' + } + }, { modifier: true, upsert: true }).to.equal(7) expectRequiredErrorLength(requiredSchema, { $setOnInsert: { @@ -538,21 +538,21 @@ describe('SimpleSchema - required', function () { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': ' ', - }, - }, { modifier: true, upsert: true }).to.equal(7); + 'optionalObject.requiredString': ' ' + } + }, { modifier: true, upsert: true }).to.equal(7) // Array of objects expectRequiredErrorLength(friendsSchema, { $setOnInsert: { friends: [{ - name: 'Bob', + name: 'Bob' }], - enemies: [], - }, - }, { modifier: true, upsert: true }).to.equal(1); - }); - }); + enemies: [] + } + }, { modifier: true, upsert: true }).to.equal(1) + }) + }) describe('modifier with $set and $setOnInsert', function () { it('valid upsert', function () { @@ -563,152 +563,152 @@ describe('SimpleSchema - required', function () { requiredString: 'test', requiredBoolean: true, requiredNumber: 1, - requiredDate: (new Date()), + requiredDate: (new Date()) }, $setOnInsert: { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, + requiredNumber: 1 }, - 'optionalObject.requiredString': 'test', - }, - }, { modifier: true, upsert: true }); + 'optionalObject.requiredString': 'test' + } + }, { modifier: true, upsert: true }) expectValid(requiredSchema, { $set: { requiredString: 'test', requiredBoolean: true, requiredNumber: 1, - requiredDate: (new Date()), + requiredDate: (new Date()) }, $setOnInsert: { requiredEmail: 'test123@sub.example.edu', requiredUrl: 'http://google.com', requiredObject: { - requiredNumber: 1, + requiredNumber: 1 }, - 'optionalObject.requiredString': 'test', - }, - }, { modifier: true, upsert: true }); - }); + 'optionalObject.requiredString': 'test' + } + }, { modifier: true, upsert: true }) + }) it('invalid upsert', function () { expectRequiredErrorLength(requiredSchema, { $setOnInsert: {}, - $set: {}, - }, { modifier: true, upsert: true }).to.equal(8); + $set: {} + }, { modifier: true, upsert: true }).to.equal(8) expectRequiredErrorLength(requiredSchema, { $set: { requiredString: null, requiredBoolean: null, requiredNumber: null, - requiredDate: null, + requiredDate: null }, $setOnInsert: { requiredEmail: null, requiredUrl: null, requiredObject: null, - 'optionalObject.requiredString': null, - }, - }, { modifier: true, upsert: true }).to.equal(9); + 'optionalObject.requiredString': null + } + }, { modifier: true, upsert: true }).to.equal(9) expectRequiredErrorLength(requiredSchema, { $set: { requiredString: undefined, requiredBoolean: undefined, requiredNumber: undefined, - requiredDate: undefined, + requiredDate: undefined }, $setOnInsert: { requiredEmail: undefined, requiredUrl: undefined, requiredObject: undefined, - 'optionalObject.requiredString': undefined, - }, - }, { modifier: true, upsert: true }).to.equal(8); + 'optionalObject.requiredString': undefined + } + }, { modifier: true, upsert: true }).to.equal(8) expectRequiredErrorLength(requiredSchema, { $set: { requiredString: '', requiredBoolean: null, requiredNumber: null, - requiredDate: null, + requiredDate: null }, $setOnInsert: { requiredEmail: '', requiredUrl: '', requiredObject: null, - 'optionalObject.requiredString': '', - }, - }, { modifier: true, upsert: true }).to.equal(5); + 'optionalObject.requiredString': '' + } + }, { modifier: true, upsert: true }).to.equal(5) expectRequiredErrorLength(requiredSchema, { $set: { requiredString: ' ', requiredBoolean: null, requiredNumber: null, - requiredDate: null, + requiredDate: null }, $setOnInsert: { requiredEmail: ' ', requiredUrl: ' ', requiredObject: null, - 'optionalObject.requiredString': ' ', - }, - }, { modifier: true, upsert: true }).to.equal(5); - }); - }); + 'optionalObject.requiredString': ' ' + } + }, { modifier: true, upsert: true }).to.equal(5) + }) + }) describe('modifier with $unset', function () { it('valid', function () { // Would not cause DB changes, so should not be an error expectValid(requiredSchema, { - $unset: {}, - }, { modifier: true }); + $unset: {} + }, { modifier: true }) // Make sure an optional can be unset when others are required // Retest with various values to be sure the value is ignored expectValid(requiredSchema, { $unset: { - anOptionalOne: 1, - }, - }, { modifier: true }); + anOptionalOne: 1 + } + }, { modifier: true }) expectValid(requiredSchema, { $unset: { - anOptionalOne: null, - }, - }, { modifier: true }); + anOptionalOne: null + } + }, { modifier: true }) expectValid(requiredSchema, { $unset: { - anOptionalOne: '', - }, - }, { modifier: true }); + anOptionalOne: '' + } + }, { modifier: true }) expectValid(requiredSchema, { $unset: { - optionalObject: '', - }, - }, { modifier: true }); + optionalObject: '' + } + }, { modifier: true }) // Array of objects expectValid(friendsSchema, { $unset: { - 'friends.1.a.b': '', - }, - }, { modifier: true }); + 'friends.1.a.b': '' + } + }, { modifier: true }) expectValid(friendsSchema, { $unset: { 'friends.1.a.b': 1, 'friends.2.a.b': 1, - 'friends.3.a.b': 1, - }, - }, { modifier: true }); - }); + 'friends.3.a.b': 1 + } + }, { modifier: true }) + }) it('invalid', function () { expectRequiredErrorLength(requiredSchema, { @@ -718,64 +718,64 @@ describe('SimpleSchema - required', function () { requiredNumber: 1, requiredDate: 1, requiredEmail: 1, - requiredUrl: 1, - }, - }, { modifier: true }).to.equal(6); + requiredUrl: 1 + } + }, { modifier: true }).to.equal(6) expectRequiredErrorLength(requiredSchema, { $unset: { - 'optionalObject.requiredString': 1, - }, - }, { modifier: true }).to.equal(1); + 'optionalObject.requiredString': 1 + } + }, { modifier: true }).to.equal(1) expectRequiredErrorLength(requiredSchema, { $unset: { - 'requiredObject.requiredNumber': 1, - }, - }, { modifier: true }).to.equal(1); + 'requiredObject.requiredNumber': 1 + } + }, { modifier: true }).to.equal(1) // Array of objects expectRequiredErrorLength(friendsSchema, { $unset: { - 'friends.1.name': 1, - }, - }, { modifier: true }).to.equal(1); + 'friends.1.name': 1 + } + }, { modifier: true }).to.equal(1) expectRequiredErrorLength(friendsSchema, { $unset: { 'friends.1.name': 1, 'friends.2.name': 1, - 'friends.3.name': 1, - }, - }, { modifier: true }).to.equal(3); - }); - }); + 'friends.3.name': 1 + } + }, { modifier: true }).to.equal(3) + }) + }) describe('modifier with $rename', function () { it('rename from optional key to another key in schema', function () { expectValid(testSchema, { $rename: { - string: 'minMaxString', - }, - }, { modifier: true }); - }); + string: 'minMaxString' + } + }, { modifier: true }) + }) it('rename from optional key to a key not in schema', function () { expectErrorLength(testSchema, { $rename: { - string: 'newString', - }, - }, { modifier: true }).to.equal(1); - }); + string: 'newString' + } + }, { modifier: true }).to.equal(1) + }) it('rename from required key', function () { expectRequiredErrorLength(requiredSchema, { $rename: { - requiredString: 'requiredUrl', - }, - }, { modifier: true }).to.equal(1); - }); - }); + requiredString: 'requiredUrl' + } + }, { modifier: true }).to.equal(1) + }) + }) describe('modifier with $push', function () { it('valid', function () { @@ -783,22 +783,22 @@ describe('SimpleSchema - required', function () { $push: { friends: { name: 'Bob', - type: 'best', - }, - }, - }, { modifier: true }).to.equal(0); - }); + type: 'best' + } + } + }, { modifier: true }).to.equal(0) + }) it('invalid', function () { expectRequiredErrorLength(friendsSchema, { $push: { friends: { - name: 'Bob', - }, - }, - }, { modifier: true }).to.equal(1); - }); - }); + name: 'Bob' + } + } + }, { modifier: true }).to.equal(1) + }) + }) describe('modifier with $addToSet', function () { it('valid', function () { @@ -806,20 +806,20 @@ describe('SimpleSchema - required', function () { $addToSet: { friends: { name: 'Bob', - type: 'best', - }, - }, - }, { modifier: true }).to.equal(0); - }); + type: 'best' + } + } + }, { modifier: true }).to.equal(0) + }) it('invalid', function () { expectRequiredErrorLength(friendsSchema, { $addToSet: { friends: { - name: 'Bob', - }, - }, - }, { modifier: true }).to.equal(1); - }); - }); -}); + name: 'Bob' + } + } + }, { modifier: true }).to.equal(1) + }) + }) +}) diff --git a/lib/SimpleSchema_rules.tests.js b/lib/SimpleSchema_rules.tests.js index 1048ebe..d0f4995 100644 --- a/lib/SimpleSchema_rules.tests.js +++ b/lib/SimpleSchema_rules.tests.js @@ -1,25 +1,25 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' describe('SimpleSchema - Rules', function () { it('Rules should be passed the object being validated', function () { const validationContext = new SimpleSchema({ foo: { - type: Number, + type: Number }, bar: { type: Number, - max() { - return this.obj.foo; - }, - }, - }).newContext(); + max () { + return this.obj.foo + } + } + }).newContext() - validationContext.validate({ foo: 5, bar: 10 }); - expect(validationContext.validationErrors().length).to.equal(1); - validationContext.validate({ foo: 10, bar: 5 }); - expect(validationContext.validationErrors().length).to.equal(0); - }); -}); + validationContext.validate({ foo: 5, bar: 10 }) + expect(validationContext.validationErrors().length).to.equal(1) + validationContext.validate({ foo: 10, bar: 5 }) + expect(validationContext.validationErrors().length).to.equal(0) + }) +}) diff --git a/lib/SimpleSchema_type.tests.js b/lib/SimpleSchema_type.tests.js index 0b80d0a..ddad8ce 100644 --- a/lib/SimpleSchema_type.tests.js +++ b/lib/SimpleSchema_type.tests.js @@ -1,25 +1,25 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import expectErrorLength from './testHelpers/expectErrorLength'; -import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength'; -import friendsSchema from './testHelpers/friendsSchema'; -import testSchema from './testHelpers/testSchema'; -import { SimpleSchema } from './SimpleSchema'; -import Address from './testHelpers/Address'; +import { expect } from 'chai' +import expectErrorLength from './testHelpers/expectErrorLength' +import expectErrorOfTypeLength from './testHelpers/expectErrorOfTypeLength' +import friendsSchema from './testHelpers/friendsSchema' +import testSchema from './testHelpers/testSchema' +import { SimpleSchema } from './SimpleSchema' +import Address from './testHelpers/Address' describe('SimpleSchema - type', function () { it('typed array', function () { const schema = new SimpleSchema({ ta: { - type: Uint8Array, - }, - }); + type: Uint8Array + } + }) expectErrorLength(schema, { - ta: new Uint8Array(100000000), - }).to.deep.equal(0); - }); + ta: new Uint8Array(100000000) + }).to.deep.equal(0) + }) it('array of objects', function () { expectErrorOfTypeLength( @@ -33,15 +33,15 @@ describe('SimpleSchema - type', function () { traits: [ { name: 'evil', - weight: 'heavy', - }, - ], - }, - ], - }, + weight: 'heavy' + } + ] + } + ] + } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, @@ -54,55 +54,55 @@ describe('SimpleSchema - type', function () { traits: [ { name: 'evil', - weight: 9.5, - }, - ], - }, - ], - }, + weight: 9.5 + } + ] + } + ] + } }, - { modifier: true }, - ).to.deep.equal(0); - }); + { modifier: true } + ).to.deep.equal(0) + }) describe('custom type', function () { it('valid', function () { const schema = new SimpleSchema({ address: { type: Address }, createdAt: { type: Date }, - file: { type: Uint8Array }, - }); + file: { type: Uint8Array } + }) expectErrorOfTypeLength(SimpleSchema.ErrorTypes.EXPECTED_TYPE, schema, { createdAt: new Date(), file: new Uint8Array([104, 101, 108, 108, 111]), - address: new Address('San Francisco', 'CA'), - }).to.deep.equal(0); - }); + address: new Address('San Francisco', 'CA') + }).to.deep.equal(0) + }) it('invalid', function () { const schema = new SimpleSchema({ address: { type: Address }, createdAt: { type: Date }, - file: { type: Uint8Array }, - }); + file: { type: Uint8Array } + }) expectErrorOfTypeLength(SimpleSchema.ErrorTypes.EXPECTED_TYPE, schema, { createdAt: {}, file: {}, - address: {}, - }).to.deep.equal(3); - }); - }); + address: {} + }).to.deep.equal(3) + }) + }) it('weird type', function () { expect(function () { // eslint-disable-next-line no-new new SimpleSchema({ - name: { type: Array[Object] }, - }); - }).to.throw(); - }); + name: { type: Array[Object] } + }) + }).to.throw() + }) describe('string', function () { it('normal', function () { @@ -110,302 +110,302 @@ describe('SimpleSchema - type', function () { SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - string: 'test', - }, - ).to.deep.equal(0); + string: 'test' + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - string: true, - }, - ).to.deep.equal(1); + string: true + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - string: 1, - }, - ).to.deep.equal(1); + string: 1 + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - string: { test: 'test' }, - }, - ).to.deep.equal(1); + string: { test: 'test' } + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - string: ['test'], - }, - ).to.deep.equal(1); + string: ['test'] + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - string: new Date(), - }, - ).to.deep.equal(1); - }); + string: new Date() + } + ).to.deep.equal(1) + }) it('modifier with $setOnInsert', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { string: 'test' }, + $setOnInsert: { string: 'test' } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { string: true }, + $setOnInsert: { string: true } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { string: 1 }, + $setOnInsert: { string: 1 } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { string: { test: 'test' } }, + $setOnInsert: { string: { test: 'test' } } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { string: ['test'] }, + $setOnInsert: { string: ['test'] } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { string: new Date() }, + $setOnInsert: { string: new Date() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); - }); + { modifier: true, upsert: true } + ).to.deep.equal(1) + }) it('modifier with $set', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { string: 'test' }, + $set: { string: 'test' } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { string: true }, + $set: { string: true } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { string: 1 }, + $set: { string: 1 } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { string: { test: 'test' } }, + $set: { string: { test: 'test' } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { string: ['test'] }, + $set: { string: ['test'] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { string: new Date() }, + $set: { string: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: 'test' }, + $push: { allowedStringsArray: 'test' } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: true }, + $push: { allowedStringsArray: true } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: 1 }, + $push: { allowedStringsArray: 1 } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: { test: 'test' } }, + $push: { allowedStringsArray: { test: 'test' } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: ['test'] }, + $push: { allowedStringsArray: ['test'] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: new Date() }, + $push: { allowedStringsArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $addToSet', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedStringsArray: 'test' }, + $addToSet: { allowedStringsArray: 'test' } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedStringsArray: true }, + $addToSet: { allowedStringsArray: true } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedStringsArray: 1 }, + $addToSet: { allowedStringsArray: 1 } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedStringsArray: { test: 'test' } }, + $addToSet: { allowedStringsArray: { test: 'test' } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedStringsArray: ['test'] }, + $addToSet: { allowedStringsArray: ['test'] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedStringsArray: new Date() }, + $addToSet: { allowedStringsArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push + $each', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: { $each: ['test', 'test'] } }, + $push: { allowedStringsArray: { $each: ['test', 'test'] } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: { $each: [true, false] } }, + $push: { allowedStringsArray: { $each: [true, false] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: { $each: [1, 2] } }, + $push: { allowedStringsArray: { $each: [1, 2] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, @@ -413,32 +413,32 @@ describe('SimpleSchema - type', function () { { $push: { allowedStringsArray: { - $each: [{ test: 'test' }, { test: 'test2' }], - }, - }, + $each: [{ test: 'test' }, { test: 'test2' }] + } + } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: { $each: [['test'], ['test']] } }, + $push: { allowedStringsArray: { $each: [['test'], ['test']] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedStringsArray: { $each: [new Date(), new Date()] } }, + $push: { allowedStringsArray: { $each: [new Date(), new Date()] } } }, - { modifier: true }, - ).to.deep.equal(2); - }); - }); + { modifier: true } + ).to.deep.equal(2) + }) + }) describe('boolean', function () { it('normal', function () { @@ -446,375 +446,375 @@ describe('SimpleSchema - type', function () { SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - boolean: true, - }, - ).to.deep.equal(0); + boolean: true + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - boolean: false, - }, - ).to.deep.equal(0); + boolean: false + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - boolean: 'true', - }, - ).to.deep.equal(1); + boolean: 'true' + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - boolean: 0, - }, - ).to.deep.equal(1); + boolean: 0 + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - boolean: { test: true }, - }, - ).to.deep.equal(1); + boolean: { test: true } + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - boolean: [false], - }, - ).to.deep.equal(1); + boolean: [false] + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - boolean: new Date(), - }, - ).to.deep.equal(1); - }); + boolean: new Date() + } + ).to.deep.equal(1) + }) it('modifier with $setOnInsert', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { boolean: true }, + $setOnInsert: { boolean: true } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { boolean: false }, + $setOnInsert: { boolean: false } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { boolean: 'true' }, + $setOnInsert: { boolean: 'true' } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { boolean: 0 }, + $setOnInsert: { boolean: 0 } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { boolean: { test: true } }, + $setOnInsert: { boolean: { test: true } } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { boolean: [false] }, + $setOnInsert: { boolean: [false] } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { boolean: new Date() }, + $setOnInsert: { boolean: new Date() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); - }); + { modifier: true, upsert: true } + ).to.deep.equal(1) + }) it('modifier with $set', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { boolean: true }, + $set: { boolean: true } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { boolean: false }, + $set: { boolean: false } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { boolean: 'true' }, + $set: { boolean: 'true' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { boolean: 0 }, + $set: { boolean: 0 } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { boolean: { test: true } }, + $set: { boolean: { test: true } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { boolean: [false] }, + $set: { boolean: [false] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { boolean: new Date() }, + $set: { boolean: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: true }, + $push: { booleanArray: true } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: false }, + $push: { booleanArray: false } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: 'true' }, + $push: { booleanArray: 'true' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: 0 }, + $push: { booleanArray: 0 } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: { test: true } }, + $push: { booleanArray: { test: true } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: [false] }, + $push: { booleanArray: [false] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: new Date() }, + $push: { booleanArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $addToSet', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { booleanArray: true }, + $addToSet: { booleanArray: true } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { booleanArray: false }, + $addToSet: { booleanArray: false } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { booleanArray: 'true' }, + $addToSet: { booleanArray: 'true' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { booleanArray: 0 }, + $addToSet: { booleanArray: 0 } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { booleanArray: { test: true } }, + $addToSet: { booleanArray: { test: true } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { booleanArray: [false] }, + $addToSet: { booleanArray: [false] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { booleanArray: new Date() }, + $addToSet: { booleanArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push + $each', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: { $each: [true, false] } }, + $push: { booleanArray: { $each: [true, false] } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: { $each: ['true', 'false'] } }, + $push: { booleanArray: { $each: ['true', 'false'] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: { $each: [0, 1] } }, + $push: { booleanArray: { $each: [0, 1] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: { $each: [{ test: true }, { test: false }] } }, + $push: { booleanArray: { $each: [{ test: true }, { test: false }] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: { $each: [[true], [false]] } }, + $push: { booleanArray: { $each: [[true], [false]] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { booleanArray: { $each: [new Date(), new Date()] } }, + $push: { booleanArray: { $each: [new Date(), new Date()] } } }, - { modifier: true }, - ).to.deep.equal(2); - }); - }); + { modifier: true } + ).to.deep.equal(2) + }) + }) describe('number', function () { it('normal', function () { @@ -822,434 +822,434 @@ describe('SimpleSchema - type', function () { SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - number: 1, - }, - ).to.deep.equal(0); + number: 1 + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - number: 0, - }, - ).to.deep.equal(0); + number: 0 + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - number: 'test', - }, - ).to.deep.equal(1); + number: 'test' + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - number: false, - }, - ).to.deep.equal(1); + number: false + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - number: { test: 1 }, - }, - ).to.deep.equal(1); + number: { test: 1 } + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - number: [1], - }, - ).to.deep.equal(1); + number: [1] + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - number: new Date(), - }, - ).to.deep.equal(1); + number: new Date() + } + ).to.deep.equal(1) // NaN does not count expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - number: NaN, - }, - ).to.deep.equal(1); - }); + number: NaN + } + ).to.deep.equal(1) + }) it('modifier with $setOnInsert', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { number: 1 }, + $setOnInsert: { number: 1 } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { number: 0 }, + $setOnInsert: { number: 0 } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { number: 'test' }, + $setOnInsert: { number: 'test' } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { number: false }, + $setOnInsert: { number: false } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { number: { test: 1 } }, + $setOnInsert: { number: { test: 1 } } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { number: [1] }, + $setOnInsert: { number: [1] } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { number: new Date() }, + $setOnInsert: { number: new Date() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) // NaN does not count expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { number: NaN }, + $setOnInsert: { number: NaN } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); - }); + { modifier: true, upsert: true } + ).to.deep.equal(1) + }) it('modifier with $set', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { number: 1 }, + $set: { number: 1 } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { number: 0 }, + $set: { number: 0 } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { number: 'test' }, + $set: { number: 'test' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { number: false }, + $set: { number: false } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { number: { test: 1 } }, + $set: { number: { test: 1 } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { number: [1] }, + $set: { number: [1] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { number: new Date() }, + $set: { number: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) // NaN does not count expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { number: NaN }, + $set: { number: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: 1 }, + $push: { allowedNumbersArray: 1 } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: 0 }, + $push: { allowedNumbersArray: 0 } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: 'test' }, + $push: { allowedNumbersArray: 'test' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: false }, + $push: { allowedNumbersArray: false } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: { test: 1 } }, + $push: { allowedNumbersArray: { test: 1 } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: [1] }, + $push: { allowedNumbersArray: [1] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: new Date() }, + $push: { allowedNumbersArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) // NaN does not count expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: NaN }, + $push: { allowedNumbersArray: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $addToSet', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedNumbersArray: 1 }, + $addToSet: { allowedNumbersArray: 1 } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedNumbersArray: 0 }, + $addToSet: { allowedNumbersArray: 0 } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedNumbersArray: 'test' }, + $addToSet: { allowedNumbersArray: 'test' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedNumbersArray: false }, + $addToSet: { allowedNumbersArray: false } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedNumbersArray: { test: 1 } }, + $addToSet: { allowedNumbersArray: { test: 1 } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedNumbersArray: [1] }, + $addToSet: { allowedNumbersArray: [1] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedNumbersArray: new Date() }, + $addToSet: { allowedNumbersArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) // NaN does not count expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { allowedNumbersArray: NaN }, + $addToSet: { allowedNumbersArray: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push + $each', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: { $each: [0, 1] } }, + $push: { allowedNumbersArray: { $each: [0, 1] } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: { $each: ['test', 'test'] } }, + $push: { allowedNumbersArray: { $each: ['test', 'test'] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: { $each: [false, true] } }, + $push: { allowedNumbersArray: { $each: [false, true] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: { $each: [{ test: 1 }, { test: 2 }] } }, + $push: { allowedNumbersArray: { $each: [{ test: 1 }, { test: 2 }] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: { $each: [[1], [2]] } }, + $push: { allowedNumbersArray: { $each: [[1], [2]] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: { $each: [new Date(), new Date()] } }, + $push: { allowedNumbersArray: { $each: [new Date(), new Date()] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) // NaN does not count expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { allowedNumbersArray: { $each: [NaN, NaN] } }, + $push: { allowedNumbersArray: { $each: [NaN, NaN] } } }, - { modifier: true }, - ).to.deep.equal(2); - }); - }); + { modifier: true } + ).to.deep.equal(2) + }) + }) describe('date', function () { it('normal', function () { @@ -1257,362 +1257,362 @@ describe('SimpleSchema - type', function () { SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - date: new Date(), - }, - ).to.deep.equal(0); + date: new Date() + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - date: 'test', - }, - ).to.deep.equal(1); + date: 'test' + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - date: false, - }, - ).to.deep.equal(1); + date: false + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - date: { test: new Date() }, - }, - ).to.deep.equal(1); + date: { test: new Date() } + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - date: [new Date()], - }, - ).to.deep.equal(1); + date: [new Date()] + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - date: 1, - }, - ).to.deep.equal(1); - }); + date: 1 + } + ).to.deep.equal(1) + }) it('modifier with $setOnInsert', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { date: new Date() }, + $setOnInsert: { date: new Date() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { date: 'test' }, + $setOnInsert: { date: 'test' } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { date: false }, + $setOnInsert: { date: false } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { date: { test: new Date() } }, + $setOnInsert: { date: { test: new Date() } } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { date: [new Date()] }, + $setOnInsert: { date: [new Date()] } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { date: 1 }, + $setOnInsert: { date: 1 } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); - }); + { modifier: true, upsert: true } + ).to.deep.equal(1) + }) it('modifier with $set', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { date: new Date() }, + $set: { date: new Date() } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { date: 'test' }, + $set: { date: 'test' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { date: false }, + $set: { date: false } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { date: { test: new Date() } }, + $set: { date: { test: new Date() } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { date: [new Date()] }, + $set: { date: [new Date()] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { date: 1 }, + $set: { date: 1 } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $currentDate', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $currentDate: { date: true }, + $currentDate: { date: true } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $currentDate: { date: { $type: 'date' } }, + $currentDate: { date: { $type: 'date' } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $currentDate: { date: { $type: 'timestamp' } }, + $currentDate: { date: { $type: 'timestamp' } } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: new Date() }, + $push: { dateArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: 'test' }, + $push: { dateArray: 'test' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: false }, + $push: { dateArray: false } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: { test: new Date() } }, + $push: { dateArray: { test: new Date() } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: [new Date()] }, + $push: { dateArray: [new Date()] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: 1 }, + $push: { dateArray: 1 } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $addToSet', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { dateArray: new Date() }, + $addToSet: { dateArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { dateArray: 'test' }, + $addToSet: { dateArray: 'test' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { dateArray: false }, + $addToSet: { dateArray: false } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { dateArray: { test: new Date() } }, + $addToSet: { dateArray: { test: new Date() } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { dateArray: [new Date()] }, + $addToSet: { dateArray: [new Date()] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { dateArray: 1 }, + $addToSet: { dateArray: 1 } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push + $each', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: { $each: [new Date(), new Date()] } }, + $push: { dateArray: { $each: [new Date(), new Date()] } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: { $each: ['test', 'test'] } }, + $push: { dateArray: { $each: ['test', 'test'] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: { $each: [false, true] } }, + $push: { dateArray: { $each: [false, true] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { $push: { - dateArray: { $each: [{ test: new Date() }, { test: new Date() }] }, - }, + dateArray: { $each: [{ test: new Date() }, { test: new Date() }] } + } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: { $each: [[new Date()], [new Date()]] } }, + $push: { dateArray: { $each: [[new Date()], [new Date()]] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { dateArray: { $each: [1, 2] } }, + $push: { dateArray: { $each: [1, 2] } } }, - { modifier: true }, - ).to.deep.equal(2); - }); - }); + { modifier: true } + ).to.deep.equal(2) + }) + }) describe('array', function () { it('normal', function () { @@ -1620,192 +1620,192 @@ describe('SimpleSchema - type', function () { SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - booleanArray: [], - }, - ).to.deep.equal(0); + booleanArray: [] + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - booleanArray: [true], - }, - ).to.deep.equal(0); + booleanArray: [true] + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - booleanArray: [false], - }, - ).to.deep.equal(0); + booleanArray: [false] + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - booleanArray: 'test', - }, - ).to.deep.equal(1); + booleanArray: 'test' + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - booleanArray: false, - }, - ).to.deep.equal(1); + booleanArray: false + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - booleanArray: { test: [] }, - }, - ).to.deep.equal(1); + booleanArray: { test: [] } + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - booleanArray: ['test'], - }, - ).to.deep.equal(1); + booleanArray: ['test'] + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - booleanArray: 1, - }, - ).to.deep.equal(1); - }); + booleanArray: 1 + } + ).to.deep.equal(1) + }) it('modifier with $setOnInsert', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { booleanArray: [true, false] }, + $setOnInsert: { booleanArray: [true, false] } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { booleanArray: 'test' }, + $setOnInsert: { booleanArray: 'test' } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { booleanArray: false }, + $setOnInsert: { booleanArray: false } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { booleanArray: { test: [false] } }, + $setOnInsert: { booleanArray: { test: [false] } } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { booleanArray: new Date() }, + $setOnInsert: { booleanArray: new Date() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { booleanArray: 1 }, + $setOnInsert: { booleanArray: 1 } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); - }); + { modifier: true, upsert: true } + ).to.deep.equal(1) + }) it('modifier with $set', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { booleanArray: [true, false] }, + $set: { booleanArray: [true, false] } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { booleanArray: 'test' }, + $set: { booleanArray: 'test' } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { booleanArray: false }, + $set: { booleanArray: false } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { booleanArray: { test: false } }, + $set: { booleanArray: { test: false } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { booleanArray: new Date() }, + $set: { booleanArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { booleanArray: 1 }, + $set: { booleanArray: 1 } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('sparse arrays', function () { const schema = new SimpleSchema({ sparse: Array, 'sparse.$': { type: String, - optional: true, - }, - }); + optional: true + } + }) expectErrorLength(schema, { - sparse: ['1', null, '2', null], - }).to.deep.equal(0); - }); + sparse: ['1', null, '2', null] + }).to.deep.equal(0) + }) it('ignores slice', function () { expectErrorLength( @@ -1815,12 +1815,12 @@ describe('SimpleSchema - type', function () { booleanArray: { $each: [false, true], $slice: -5 }, dateArray: { $each: [new Date(), new Date()], $slice: -5 }, allowedStringsArray: { $each: ['tuna', 'fish'], $slice: -5 }, - allowedNumbersArray: { $each: [2, 1], $slice: -5 }, - }, + allowedNumbersArray: { $each: [2, 1], $slice: -5 } + } }, - { modifier: true }, - ).to.deep.equal(0); - }); + { modifier: true } + ).to.deep.equal(0) + }) it('ignores pull', function () { expectErrorLength( @@ -1830,12 +1830,12 @@ describe('SimpleSchema - type', function () { booleanArray: 'foo', dateArray: 'foo', allowedStringsArray: 'foo', - allowedNumbersArray: 200, - }, + allowedNumbersArray: 200 + } }, - { modifier: true }, - ).to.deep.equal(0); - }); + { modifier: true } + ).to.deep.equal(0) + }) it('ignores pull + $each', function () { expectErrorLength( @@ -1845,12 +1845,12 @@ describe('SimpleSchema - type', function () { booleanArray: { $each: ['foo', 'bar'] }, dateArray: { $each: ['foo', 'bar'] }, allowedStringsArray: { $each: ['foo', 'bar'] }, - allowedNumbersArray: { $each: [200, 500] }, - }, + allowedNumbersArray: { $each: [200, 500] } + } }, - { modifier: true }, - ).to.deep.equal(0); - }); + { modifier: true } + ).to.deep.equal(0) + }) it('ignores pullAll', function () { expectErrorLength( @@ -1860,12 +1860,12 @@ describe('SimpleSchema - type', function () { booleanArray: ['foo', 'bar'], dateArray: ['foo', 'bar'], allowedStringsArray: ['foo', 'bar'], - allowedNumbersArray: [200, 500], - }, + allowedNumbersArray: [200, 500] + } }, - { modifier: true }, - ).to.deep.equal(0); - }); + { modifier: true } + ).to.deep.equal(0) + }) it('ignores pop', function () { expectErrorLength( @@ -1875,11 +1875,11 @@ describe('SimpleSchema - type', function () { booleanArray: 1, dateArray: 1, allowedStringsArray: 1, - allowedNumbersArray: 1, - }, + allowedNumbersArray: 1 + } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorLength( testSchema, @@ -1888,13 +1888,13 @@ describe('SimpleSchema - type', function () { booleanArray: -1, dateArray: -1, allowedStringsArray: -1, - allowedNumbersArray: -1, - }, + allowedNumbersArray: -1 + } }, - { modifier: true }, - ).to.deep.equal(0); - }); - }); + { modifier: true } + ).to.deep.equal(0) + }) + }) describe('object', function () { it('normal', function () { @@ -1902,375 +1902,375 @@ describe('SimpleSchema - type', function () { SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - sub: {}, - }, - ).to.deep.equal(0); + sub: {} + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - sub: { number: 1 }, - }, - ).to.deep.equal(0); + sub: { number: 1 } + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - sub: [], - }, - ).to.deep.equal(1); + sub: [] + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - sub: new Set(), - }, - ).to.deep.equal(1); + sub: new Set() + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - sub: new Map(), - }, - ).to.deep.equal(1); + sub: new Map() + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - sub: new Date(), - }, - ).to.deep.equal(1); + sub: new Date() + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - sub: NaN, - }, - ).to.deep.equal(1); - }); + sub: NaN + } + ).to.deep.equal(1) + }) it('modifier with $setOnInsert', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { sub: {} }, + $setOnInsert: { sub: {} } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { sub: { number: 1 } }, + $setOnInsert: { sub: { number: 1 } } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { sub: [] }, + $setOnInsert: { sub: [] } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { sub: new Set() }, + $setOnInsert: { sub: new Set() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { sub: new Map() }, + $setOnInsert: { sub: new Map() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { sub: new Date() }, + $setOnInsert: { sub: new Date() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { sub: NaN }, + $setOnInsert: { sub: NaN } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); - }); + { modifier: true, upsert: true } + ).to.deep.equal(1) + }) it('modifier with $set', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { sub: {} }, + $set: { sub: {} } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { sub: { number: 1 } }, + $set: { sub: { number: 1 } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { sub: [] }, + $set: { sub: [] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { sub: new Set() }, + $set: { sub: new Set() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { sub: new Map() }, + $set: { sub: new Map() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { sub: new Date() }, + $set: { sub: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { sub: NaN }, + $set: { sub: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: {} }, + $push: { objectArray: {} } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: { number: 1 } }, + $push: { objectArray: { number: 1 } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: [] }, + $push: { objectArray: [] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: new Set() }, + $push: { objectArray: new Set() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: new Map() }, + $push: { objectArray: new Map() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: new Date() }, + $push: { objectArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: NaN }, + $push: { objectArray: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $addToSet', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { objectArray: {} }, + $addToSet: { objectArray: {} } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { objectArray: { number: 1 } }, + $addToSet: { objectArray: { number: 1 } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { objectArray: [] }, + $addToSet: { objectArray: [] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { objectArray: new Set() }, + $addToSet: { objectArray: new Set() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { objectArray: new Map() }, + $addToSet: { objectArray: new Map() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { objectArray: new Date() }, + $addToSet: { objectArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { objectArray: NaN }, + $addToSet: { objectArray: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push + $each', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: { $each: [{}, { number: 1 }] } }, + $push: { objectArray: { $each: [{}, { number: 1 }] } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: { $each: [{}, []] } }, + $push: { objectArray: { $each: [{}, []] } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: { $each: [new Set(), new Set()] } }, + $push: { objectArray: { $each: [new Set(), new Set()] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: { $each: [new Map(), new Map()] } }, + $push: { objectArray: { $each: [new Map(), new Map()] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: { $each: [new Date(), {}] } }, + $push: { objectArray: { $each: [new Date(), {}] } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { objectArray: { $each: [NaN, NaN] } }, + $push: { objectArray: { $each: [NaN, NaN] } } }, - { modifier: true }, - ).to.deep.equal(2); - }); - }); + { modifier: true } + ).to.deep.equal(2) + }) + }) describe('simple schema instance', function () { it('normal', function () { @@ -2278,318 +2278,318 @@ describe('SimpleSchema - type', function () { SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - refObject: {}, - }, - ).to.deep.equal(0); + refObject: {} + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - refObject: { string: 'test', number: 1 }, - }, - ).to.deep.equal(0); + refObject: { string: 'test', number: 1 } + } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - refObject: [], - }, - ).to.deep.equal(1); + refObject: [] + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - refObject: new Set(), - }, - ).to.deep.equal(1); + refObject: new Set() + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - refObject: new Map(), - }, - ).to.deep.equal(1); + refObject: new Map() + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - refObject: new Date(), - }, - ).to.deep.equal(1); + refObject: new Date() + } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - refObject: NaN, - }, - ).to.deep.equal(1); - }); + refObject: NaN + } + ).to.deep.equal(1) + }) it('modifier with $setOnInsert', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { refObject: {} }, + $setOnInsert: { refObject: {} } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { refObject: { string: 'test', number: 1 } }, + $setOnInsert: { refObject: { string: 'test', number: 1 } } }, - { modifier: true, upsert: true }, - ).to.deep.equal(0); + { modifier: true, upsert: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { refObject: [] }, + $setOnInsert: { refObject: [] } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { refObject: new Set() }, + $setOnInsert: { refObject: new Set() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { refObject: new Map() }, + $setOnInsert: { refObject: new Map() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { refObject: new Date() }, + $setOnInsert: { refObject: new Date() } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); + { modifier: true, upsert: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $setOnInsert: { refObject: NaN }, + $setOnInsert: { refObject: NaN } }, - { modifier: true, upsert: true }, - ).to.deep.equal(1); - }); + { modifier: true, upsert: true } + ).to.deep.equal(1) + }) it('modifier with $set', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { refObject: {} }, + $set: { refObject: {} } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { refObject: { string: 'test', number: 1 } }, + $set: { refObject: { string: 'test', number: 1 } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { refObject: [] }, + $set: { refObject: [] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { refObject: new Set() }, + $set: { refObject: new Set() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { refObject: new Map() }, + $set: { refObject: new Map() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { refObject: new Date() }, + $set: { refObject: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $set: { refObject: NaN }, + $set: { refObject: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: {} }, + $push: { refSchemaArray: {} } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: { string: 'test', number: 1 } }, + $push: { refSchemaArray: { string: 'test', number: 1 } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: [] }, + $push: { refSchemaArray: [] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: new Set() }, + $push: { refSchemaArray: new Set() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: new Map() }, + $push: { refSchemaArray: new Map() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: new Date() }, + $push: { refSchemaArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: NaN }, + $push: { refSchemaArray: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $addToSet', function () { expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { refSchemaArray: {} }, + $addToSet: { refSchemaArray: {} } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { refSchemaArray: { string: 'test', number: 1 } }, + $addToSet: { refSchemaArray: { string: 'test', number: 1 } } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { refSchemaArray: [] }, + $addToSet: { refSchemaArray: [] } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { refSchemaArray: new Set() }, + $addToSet: { refSchemaArray: new Set() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { refSchemaArray: new Map() }, + $addToSet: { refSchemaArray: new Map() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { refSchemaArray: new Date() }, + $addToSet: { refSchemaArray: new Date() } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $addToSet: { refSchemaArray: NaN }, + $addToSet: { refSchemaArray: NaN } }, - { modifier: true }, - ).to.deep.equal(1); - }); + { modifier: true } + ).to.deep.equal(1) + }) it('modifier with $push + $each', function () { expectErrorOfTypeLength( @@ -2598,57 +2598,57 @@ describe('SimpleSchema - type', function () { { $push: { refSchemaArray: { - $each: [{}, { number: 1 }, { string: 'test', number: 1 }], - }, - }, + $each: [{}, { number: 1 }, { string: 'test', number: 1 }] + } + } }, - { modifier: true }, - ).to.deep.equal(0); + { modifier: true } + ).to.deep.equal(0) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: { $each: [{}, []] } }, + $push: { refSchemaArray: { $each: [{}, []] } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: { $each: [new Set(), new Set()] } }, + $push: { refSchemaArray: { $each: [new Set(), new Set()] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: { $each: [new Map(), new Map()] } }, + $push: { refSchemaArray: { $each: [new Map(), new Map()] } } }, - { modifier: true }, - ).to.deep.equal(2); + { modifier: true } + ).to.deep.equal(2) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: { $each: [new Date(), {}] } }, + $push: { refSchemaArray: { $each: [new Date(), {}] } } }, - { modifier: true }, - ).to.deep.equal(1); + { modifier: true } + ).to.deep.equal(1) expectErrorOfTypeLength( SimpleSchema.ErrorTypes.EXPECTED_TYPE, testSchema, { - $push: { refSchemaArray: { $each: [NaN, NaN] } }, + $push: { refSchemaArray: { $each: [NaN, NaN] } } }, - { modifier: true }, - ).to.deep.equal(2); - }); - }); -}); + { modifier: true } + ).to.deep.equal(2) + }) + }) +}) diff --git a/lib/ValidationContext.js b/lib/ValidationContext.js index 57ce001..31b5ce1 100644 --- a/lib/ValidationContext.js +++ b/lib/ValidationContext.js @@ -1,5 +1,5 @@ -import MongoObject from 'mongo-object'; -import doValidation from './doValidation'; +import MongoObject from 'mongo-object' +import doValidation from './doValidation' /** * @typedef ValidationError @@ -20,34 +20,34 @@ export default class ValidationContext { * @param {SimpleSchema} ss SimpleSchema instance to use for validation * @param {String} [name] Optional context name, accessible on context.name. */ - constructor(ss, name) { - this.name = name; + constructor (ss, name) { + this.name = name - this._simpleSchema = ss; - this._schema = ss.schema(); - this._schemaKeys = Object.keys(this._schema); - this._validationErrors = []; - this._deps = {}; + this._simpleSchema = ss + this._schema = ss.schema() + this._schemaKeys = Object.keys(this._schema) + this._validationErrors = [] + this._deps = {} // Set up validation dependencies - const { tracker } = ss._constructorOptions; - this.reactive(tracker); + const { tracker } = ss._constructorOptions + this.reactive(tracker) } - //--------------------------------------------------------------------------- + // --------------------------------------------------------------------------- // PUBLIC - //--------------------------------------------------------------------------- + // --------------------------------------------------------------------------- /** * Makes this validation context * reactive for Meteor-Tracker. * @param tracker {Tracker} */ - reactive(tracker) { + reactive (tracker) { if (tracker && Object.keys(this._deps).length === 0) { - this._depsAny = new tracker.Dependency(); + this._depsAny = new tracker.Dependency() this._schemaKeys.forEach((key) => { - this._deps[key] = new tracker.Dependency(); - }); + this._deps[key] = new tracker.Dependency() + }) } } @@ -56,35 +56,35 @@ export default class ValidationContext { * Reactive. * @param errors ValidationError[] */ - setValidationErrors(errors) { - const previousValidationErrors = this._validationErrors.map((o) => o.name); - const newValidationErrors = errors.map((o) => o.name); + setValidationErrors (errors) { + const previousValidationErrors = this._validationErrors.map((o) => o.name) + const newValidationErrors = errors.map((o) => o.name) - this._validationErrors = errors; + this._validationErrors = errors // Mark all previous plus all new as changed - const changedKeys = previousValidationErrors.concat(newValidationErrors); - this._markKeysChanged(changedKeys); + const changedKeys = previousValidationErrors.concat(newValidationErrors) + this._markKeysChanged(changedKeys) } /** * Adds new validation errors to the list. * @param errors ValidationError[] */ - addValidationErrors(errors) { - const newValidationErrors = errors.map((o) => o.name); + addValidationErrors (errors) { + const newValidationErrors = errors.map((o) => o.name) - errors.forEach((error) => this._validationErrors.push(error)); + errors.forEach((error) => this._validationErrors.push(error)) // Mark all new as changed - this._markKeysChanged(newValidationErrors); + this._markKeysChanged(newValidationErrors) } /** * Flushes/empties the list of validation errors. */ - reset() { - this.setValidationErrors([]); + reset () { + this.setValidationErrors([]) } /** @@ -94,12 +94,12 @@ export default class ValidationContext { * to explcitly call this. If you do, you need to wrap it using `MongoObject.makeKeyGeneric` * @return {ValidationError|undefined} */ - getErrorForKey(key, genericKey = MongoObject.makeKeyGeneric(key)) { - const errors = this._validationErrors; - const errorForKey = errors.find((error) => error.name === key); - if (errorForKey) return errorForKey; + getErrorForKey (key, genericKey = MongoObject.makeKeyGeneric(key)) { + const errors = this._validationErrors + const errorForKey = errors.find((error) => error.name === key) + if (errorForKey) return errorForKey - return errors.find((error) => error.name === genericKey); + return errors.find((error) => error.name === genericKey) } /** @@ -108,10 +108,10 @@ export default class ValidationContext { * @param genericKey {string} * @return {boolean} */ - keyIsInvalid(key, genericKey = MongoObject.makeKeyGeneric(key)) { - if (Object.prototype.hasOwnProperty.call(this._deps, genericKey)) this._deps[genericKey].depend(); + keyIsInvalid (key, genericKey = MongoObject.makeKeyGeneric(key)) { + if (Object.prototype.hasOwnProperty.call(this._deps, genericKey)) this._deps[genericKey].depend() - return this._keyIsInvalid(key, genericKey); + return this._keyIsInvalid(key, genericKey) } /** @@ -120,13 +120,13 @@ export default class ValidationContext { * @param genericKey * @return {string|*} */ - keyErrorMessage(key, genericKey = MongoObject.makeKeyGeneric(key)) { - if (Object.prototype.hasOwnProperty.call(this._deps, genericKey)) this._deps[genericKey].depend(); + keyErrorMessage (key, genericKey = MongoObject.makeKeyGeneric(key)) { + if (Object.prototype.hasOwnProperty.call(this._deps, genericKey)) this._deps[genericKey].depend() - const errorObj = this.getErrorForKey(key, genericKey); - if (!errorObj) return ''; + const errorObj = this.getErrorForKey(key, genericKey) + if (!errorObj) return '' - return this._simpleSchema.messageForError(errorObj); + return this._simpleSchema.messageForError(errorObj) } /** @@ -141,13 +141,13 @@ export default class ValidationContext { * @param isUpsert {boolean=} set to true if the document contains upsert modifiers * @return {boolean} true if no ValidationError was found, otherwise false */ - validate(obj, { + validate (obj, { extendedCustomContext = {}, ignore: ignoreTypes = [], keys: keysToValidate, modifier: isModifier = false, mongoObject, - upsert: isUpsert = false, + upsert: isUpsert = false } = {}) { const validationErrors = doValidation({ extendedCustomContext, @@ -158,8 +158,8 @@ export default class ValidationContext { mongoObject, obj, schema: this._simpleSchema, - validationContext: this, - }); + validationContext: this + }) if (keysToValidate) { // We have only revalidated the listed keys, so if there @@ -167,58 +167,58 @@ export default class ValidationContext { // we should keep these errors. /* eslint-disable no-restricted-syntax */ for (const error of this._validationErrors) { - const wasValidated = keysToValidate.some((key) => key === error.name || error.name.startsWith(`${key}.`)); - if (!wasValidated) validationErrors.push(error); + const wasValidated = keysToValidate.some((key) => key === error.name || error.name.startsWith(`${key}.`)) + if (!wasValidated) validationErrors.push(error) } /* eslint-enable no-restricted-syntax */ } - this.setValidationErrors(validationErrors); + this.setValidationErrors(validationErrors) // Return true if it was valid; otherwise, return false - return !validationErrors.length; + return !validationErrors.length } /** * returns if this context has no errors. reactive. * @return {boolean} */ - isValid() { - this._depsAny && this._depsAny.depend(); - return this._validationErrors.length === 0; + isValid () { + this._depsAny && this._depsAny.depend() + return this._validationErrors.length === 0 } /** * returns the list of validation errors. reactive. * @return {ValidationError[]} */ - validationErrors() { - this._depsAny && this._depsAny.depend(); - return this._validationErrors; + validationErrors () { + this._depsAny && this._depsAny.depend() + return this._validationErrors } - clean(...args) { - return this._simpleSchema.clean(...args); + clean (...args) { + return this._simpleSchema.clean(...args) } - //--------------------------------------------------------------------------- + // --------------------------------------------------------------------------- // PRIVATE - //--------------------------------------------------------------------------- + // --------------------------------------------------------------------------- - _markKeyChanged(key) { - const genericKey = MongoObject.makeKeyGeneric(key); - if (Object.prototype.hasOwnProperty.call(this._deps, genericKey)) this._deps[genericKey].changed(); + _markKeyChanged (key) { + const genericKey = MongoObject.makeKeyGeneric(key) + if (Object.prototype.hasOwnProperty.call(this._deps, genericKey)) this._deps[genericKey].changed() } - _markKeysChanged(keys) { - if (!keys || !Array.isArray(keys) || !keys.length) return; + _markKeysChanged (keys) { + if (!keys || !Array.isArray(keys) || !keys.length) return - keys.forEach((key) => this._markKeyChanged(key)); + keys.forEach((key) => this._markKeyChanged(key)) - this._depsAny && this._depsAny.changed(); + this._depsAny && this._depsAny.changed() } - _keyIsInvalid(key, genericKey) { - return !!this.getErrorForKey(key, genericKey); + _keyIsInvalid (key, genericKey) { + return !!this.getErrorForKey(key, genericKey) } } diff --git a/lib/clean.js b/lib/clean.js index 4266d68..cb93f2f 100644 --- a/lib/clean.js +++ b/lib/clean.js @@ -1,12 +1,12 @@ -import clone from 'clone'; -import MongoObject from 'mongo-object'; -import { isEmptyObject, looksLikeModifier } from './utility'; -import { SimpleSchema } from './SimpleSchema'; -import convertToProperType from './clean/convertToProperType'; -import setAutoValues from './clean/setAutoValues'; -import typeValidator from './validation/typeValidator'; +import clone from 'clone' +import MongoObject from 'mongo-object' +import { isEmptyObject, looksLikeModifier } from './utility' +import { SimpleSchema } from './SimpleSchema' +import convertToProperType from './clean/convertToProperType' +import setAutoValues from './clean/setAutoValues' +import typeValidator from './validation/typeValidator' -const operatorsToIgnoreValue = ['$unset', '$currentDate']; +const operatorsToIgnoreValue = ['$unset', '$currentDate'] /** * @param {SimpleSchema} ss - A SimpleSchema instance @@ -30,68 +30,68 @@ const operatorsToIgnoreValue = ['$unset', '$currentDate']; * type convert where possible, and inject automatic/default values. Use the options * to skip one or more of these. */ -async function clean(ss, doc, options = {}) { +async function clean (ss, doc, options = {}) { // By default, doc will be filtered and autoconverted options = { isModifier: looksLikeModifier(doc), isUpsert: false, ...ss._cleanOptions, - ...options, - }; + ...options + } // Clone so we do not mutate - const cleanDoc = options.mutate ? doc : clone(doc); + const cleanDoc = options.mutate ? doc : clone(doc) - const mongoObject = options.mongoObject || new MongoObject(cleanDoc, ss.blackboxKeys()); + const mongoObject = options.mongoObject || new MongoObject(cleanDoc, ss.blackboxKeys()) // Clean loop if ( - options.filter - || options.autoConvert - || options.removeEmptyStrings - || options.trimStrings + options.filter || + options.autoConvert || + options.removeEmptyStrings || + options.trimStrings ) { - const removedPositions = []; // For removing now-empty objects after + const removedPositions = [] // For removing now-empty objects after mongoObject.forEachNode( - function eachNode() { + function eachNode () { // The value of a $unset is irrelevant, so no point in cleaning it. // Also we do not care if fields not in the schema are unset. // Other operators also have values that we wouldn't want to clean. - if (operatorsToIgnoreValue.includes(this.operator)) return; + if (operatorsToIgnoreValue.includes(this.operator)) return - const gKey = this.genericKey; - if (!gKey) return; + const gKey = this.genericKey + if (!gKey) return - let val = this.value; - if (val === undefined) return; + let val = this.value + if (val === undefined) return - let p; + let p // Filter out props if necessary if ( - (options.filter && !ss.allowsKey(gKey)) - || (options.removeNullsFromArrays && this.isArrayItem && val === null) + (options.filter && !ss.allowsKey(gKey)) || + (options.removeNullsFromArrays && this.isArrayItem && val === null) ) { // XXX Special handling for $each; maybe this could be made nicer if (this.position.slice(-7) === '[$each]') { - mongoObject.removeValueForPosition(this.position.slice(0, -7)); - removedPositions.push(this.position.slice(0, -7)); + mongoObject.removeValueForPosition(this.position.slice(0, -7)) + removedPositions.push(this.position.slice(0, -7)) } else { - this.remove(); - removedPositions.push(this.position); + this.remove() + removedPositions.push(this.position) } if (SimpleSchema.debug) { console.info( - `SimpleSchema.clean: filtered out value that would have affected key "${gKey}", which is not allowed by the schema`, - ); + `SimpleSchema.clean: filtered out value that would have affected key "${gKey}", which is not allowed by the schema` + ) } - return; // no reason to do more + return // no reason to do more } - const outerDef = ss.schema(gKey); - const defs = outerDef && outerDef.type.definitions; - const def = defs && defs[0]; + const outerDef = ss.schema(gKey) + const defs = outerDef && outerDef.type.definitions + const def = defs && defs[0] // Autoconvert values if requested and if possible if (options.autoConvert && def) { @@ -99,20 +99,20 @@ async function clean(ss, doc, options = {}) { const errors = typeValidator.call({ valueShouldBeChecked: true, definition, - value: val, - }); - return errors === undefined; - }); + value: val + }) + return errors === undefined + }) if (!isValidType) { - const newVal = convertToProperType(val, def.type); + const newVal = convertToProperType(val, def.type) if (newVal !== undefined && newVal !== val) { - SimpleSchema.debug - && console.info( - `SimpleSchema.clean: autoconverted value ${val} from ${typeof val} to ${typeof newVal} for ${gKey}`, - ); - val = newVal; - this.updateValue(newVal); + SimpleSchema.debug && + console.info( + `SimpleSchema.clean: autoconverted value ${val} from ${typeof val} to ${typeof newVal} for ${gKey}` + ) + val = newVal + this.updateValue(newVal) } } } @@ -122,12 +122,12 @@ async function clean(ss, doc, options = {}) { // 2. The field is not in the schema OR is in the schema with `trim` !== `false` AND // 3. The value is a string. if ( - options.trimStrings - && (!def || def.trim !== false) - && typeof val === 'string' + options.trimStrings && + (!def || def.trim !== false) && + typeof val === 'string' ) { - val = val.trim(); - this.updateValue(val); + val = val.trim() + this.updateValue(val) } // Remove empty strings if @@ -135,66 +135,66 @@ async function clean(ss, doc, options = {}) { // 2. The value is in a normal object or in the $set part of a modifier // 3. The value is an empty string. if ( - options.removeEmptyStrings - && (!this.operator || this.operator === '$set') - && typeof val === 'string' - && !val.length + options.removeEmptyStrings && + (!this.operator || this.operator === '$set') && + typeof val === 'string' && + !val.length ) { // For a document, we remove any fields that are being set to an empty string - this.remove(); + this.remove() // For a modifier, we $unset any fields that are being set to an empty string. // But only if we're not already within an entire object that is being set. if ( - this.operator === '$set' - && this.position.match(/\[/g).length < 2 + this.operator === '$set' && + this.position.match(/\[/g).length < 2 ) { - p = this.position.replace('$set', '$unset'); - mongoObject.setValueForPosition(p, ''); + p = this.position.replace('$set', '$unset') + mongoObject.setValueForPosition(p, '') } } }, - { endPointsOnly: false }, - ); + { endPointsOnly: false } + ) // Remove any objects that are now empty after filtering removedPositions.forEach((removedPosition) => { - const lastBrace = removedPosition.lastIndexOf('['); + const lastBrace = removedPosition.lastIndexOf('[') if (lastBrace !== -1) { - const removedPositionParent = removedPosition.slice(0, lastBrace); - const value = mongoObject.getValueForPosition(removedPositionParent); - if (isEmptyObject(value)) mongoObject.removeValueForPosition(removedPositionParent); + const removedPositionParent = removedPosition.slice(0, lastBrace) + const value = mongoObject.getValueForPosition(removedPositionParent) + if (isEmptyObject(value)) mongoObject.removeValueForPosition(removedPositionParent) } - }); + }) - mongoObject.removeArrayItems(); + mongoObject.removeArrayItems() } // Set automatic values - options.getAutoValues - && await setAutoValues( + options.getAutoValues && + await setAutoValues( ss.autoValueFunctions(), mongoObject, options.isModifier, options.isUpsert, - options.extendAutoValueContext, - ); + options.extendAutoValueContext + ) // Ensure we don't have any operators set to an empty object // since MongoDB 2.6+ will throw errors. if (options.isModifier) { Object.keys(cleanDoc || {}).forEach((op) => { - const operatorValue = cleanDoc[op]; + const operatorValue = cleanDoc[op] if ( - typeof operatorValue === 'object' - && operatorValue !== null - && isEmptyObject(operatorValue) + typeof operatorValue === 'object' && + operatorValue !== null && + isEmptyObject(operatorValue) ) { - delete cleanDoc[op]; + delete cleanDoc[op] } - }); + }) } - return cleanDoc; + return cleanDoc } -export default clean; +export default clean diff --git a/lib/clean.tests.js b/lib/clean.tests.js index 272a084..406d717 100644 --- a/lib/clean.tests.js +++ b/lib/clean.tests.js @@ -1,104 +1,104 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; -import Address from './testHelpers/Address'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' +import Address from './testHelpers/Address' const ss = new SimpleSchema({ string: { type: String, - optional: true, + optional: true }, minMaxString: { type: String, optional: true, min: 10, max: 20, - regEx: /^[a-z0-9_]+$/, + regEx: /^[a-z0-9_]+$/ }, minMaxStringArray: { type: Array, optional: true, minCount: 1, - maxCount: 2, + maxCount: 2 }, 'minMaxStringArray.$': { type: String, min: 10, - max: 20, + max: 20 }, allowedStrings: { type: String, optional: true, - allowedValues: ['tuna', 'fish', 'salad'], + allowedValues: ['tuna', 'fish', 'salad'] }, allowedStringsArray: { type: Array, - optional: true, + optional: true }, 'allowedStringsArray.$': { type: String, - allowedValues: ['tuna', 'fish', 'salad'], + allowedValues: ['tuna', 'fish', 'salad'] }, boolean: { type: Boolean, - optional: true, + optional: true }, booleanArray: { type: Array, - optional: true, + optional: true }, 'booleanArray.$': { - type: Boolean, + type: Boolean }, objectArray: { type: Array, - optional: true, + optional: true }, 'objectArray.$': { - type: Object, + type: Object }, 'objectArray.$.boolean': { type: Boolean, - defaultValue: false, + defaultValue: false }, number: { type: SimpleSchema.Integer, - optional: true, + optional: true }, sub: { type: Object, - optional: true, + optional: true }, 'sub.number': { type: SimpleSchema.Integer, - optional: true, + optional: true }, minMaxNumber: { type: SimpleSchema.Integer, optional: true, min: 10, - max: 20, + max: 20 }, minZero: { type: SimpleSchema.Integer, optional: true, - min: 0, + min: 0 }, maxZero: { type: SimpleSchema.Integer, optional: true, - max: 0, + max: 0 }, minMaxNumberCalculated: { type: SimpleSchema.Integer, optional: true, - min() { - return 10; - }, - max() { - return 20; + min () { + return 10 }, + max () { + return 20 + } }, minMaxNumberExclusive: { type: SimpleSchema.Integer, @@ -106,7 +106,7 @@ const ss = new SimpleSchema({ min: 10, max: 20, exclusiveMax: true, - exclusiveMin: true, + exclusiveMin: true }, minMaxNumberInclusive: { type: SimpleSchema.Integer, @@ -114,84 +114,84 @@ const ss = new SimpleSchema({ min: 10, max: 20, exclusiveMax: false, - exclusiveMin: false, + exclusiveMin: false }, allowedNumbers: { type: SimpleSchema.Integer, optional: true, - allowedValues: [1, 2, 3], + allowedValues: [1, 2, 3] }, allowedNumbersArray: { type: Array, - optional: true, + optional: true }, 'allowedNumbersArray.$': { type: SimpleSchema.Integer, - allowedValues: [1, 2, 3], + allowedValues: [1, 2, 3] }, decimal: { type: Number, - optional: true, + optional: true }, date: { type: Date, - optional: true, + optional: true }, dateArray: { type: Array, - optional: true, + optional: true }, 'dateArray.$': { - type: Date, + type: Date }, minMaxDate: { type: Date, optional: true, min: new Date(Date.UTC(2013, 0, 1)), - max: new Date(Date.UTC(2013, 11, 31)), + max: new Date(Date.UTC(2013, 11, 31)) }, minMaxDateCalculated: { type: Date, optional: true, - min() { - return new Date(Date.UTC(2013, 0, 1)); - }, - max() { - return new Date(Date.UTC(2013, 11, 31)); + min () { + return new Date(Date.UTC(2013, 0, 1)) }, + max () { + return new Date(Date.UTC(2013, 11, 31)) + } }, email: { type: String, regEx: SimpleSchema.RegEx.Email, - optional: true, + optional: true }, url: { type: String, regEx: SimpleSchema.RegEx.Url, - optional: true, + optional: true }, customObject: { type: Address, optional: true, - blackbox: true, + blackbox: true }, blackBoxObject: { type: Object, optional: true, - blackbox: true, + blackbox: true }, noTrimString: { type: String, optional: true, - trim: false, - }, -}); + trim: false + } +}) -function getTest(given, expected, isModifier) { +function getTest (given, expected, isModifier) { return async function () { - await ss.clean(given, { isModifier, mutate: true }); - expect(given).to.deep.equal(expected); - }; + await ss.clean(given, { isModifier, mutate: true }) + expect(given).to.deep.equal(expected) + } } describe('clean', function () { @@ -201,57 +201,57 @@ describe('clean', function () { getTest( { string: 'This is a string' }, { string: 'This is a string' }, - false, - ), - ); + false + ) + ) it( 'when you clean a bad object it is now good', getTest( { string: 'This is a string', admin: true }, { string: 'This is a string' }, - false, - ), - ); - it('type conversion works', getTest({ string: 1 }, { string: '1' }, false)); - it('remove empty strings', getTest({ string: '' }, {}, false)); + false + ) + ) + it('type conversion works', getTest({ string: 1 }, { string: '1' }, false)) + it('remove empty strings', getTest({ string: '' }, {}, false)) it( 'remove whitespace only strings (trimmed to empty strings)', - getTest({ string: ' ' }, {}, false), - ); + getTest({ string: ' ' }, {}, false) + ) - const myObj = new Address('New York', 'NY'); + const myObj = new Address('New York', 'NY') it( 'when you clean a good custom object it is still good', - getTest({ customObject: myObj }, { customObject: myObj }, false), - ); + getTest({ customObject: myObj }, { customObject: myObj }, false) + ) const myObj2 = { foo: 'bar', - 'foobar.foobar': 10000, - }; + 'foobar.foobar': 10000 + } it( 'when you clean a good blackbox object it is still good', - getTest({ blackBoxObject: myObj2 }, { blackBoxObject: myObj2 }, false), - ); + getTest({ blackBoxObject: myObj2 }, { blackBoxObject: myObj2 }, false) + ) const myObj3 = { string: 't', - length: 5, - }; + length: 5 + } it( 'when you clean an object with a length property, the length property should be removed', - getTest(myObj3, { string: 't' }, false), - ); + getTest(myObj3, { string: 't' }, false) + ) const myObj4 = { string: 't', - length: null, - }; + length: null + } it( 'when you clean an object with a length null, the length property should be removed', - getTest(myObj4, { string: 't' }, false), - ); - }); + getTest(myObj4, { string: 't' }, false) + ) + }) describe('$set', function () { it( @@ -259,28 +259,28 @@ describe('clean', function () { getTest( { $set: { string: 'This is a string' } }, { $set: { string: 'This is a string' } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $set: { string: 'This is a string', admin: true } }, { $set: { string: 'This is a string' } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', - getTest({ $set: { string: 1 } }, { $set: { string: '1' } }, true), - ); + getTest({ $set: { string: 1 } }, { $set: { string: '1' } }, true) + ) // $set must be removed, too, because Mongo 2.6+ throws errors when operator object is empty it( 'move empty strings to $unset', - getTest({ $set: { string: '' } }, { $unset: { string: '' } }, true), - ); - }); + getTest({ $set: { string: '' } }, { $unset: { string: '' } }, true) + ) + }) describe('$unset', function () { // We don't want the filter option to apply to $unset operator because it should be fine @@ -289,21 +289,21 @@ describe('clean', function () { it( 'when you clean a good object it is still good', - getTest({ $unset: { string: null } }, { $unset: { string: null } }, true), - ); + getTest({ $unset: { string: null } }, { $unset: { string: null } }, true) + ) it( 'when you clean an object with extra unset keys, they stay there', getTest( { $unset: { string: null, admin: null } }, { $unset: { string: null, admin: null } }, - true, - ), - ); + true + ) + ) it( 'cleaning does not type convert the $unset value because it is a meaningless value', - getTest({ $unset: { string: 1 } }, { $unset: { string: 1 } }, true), - ); - }); + getTest({ $unset: { string: 1 } }, { $unset: { string: 1 } }, true) + ) + }) describe('$setOnInsert', function () { it( @@ -311,41 +311,41 @@ describe('clean', function () { getTest( { $setOnInsert: { string: 'This is a string' } }, { $setOnInsert: { string: 'This is a string' } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $setOnInsert: { string: 'This is a string', admin: true } }, { $setOnInsert: { string: 'This is a string' } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', getTest( { $setOnInsert: { string: 1 } }, { $setOnInsert: { string: '1' } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$inc', function () { it( 'when you clean a good object it is still good', - getTest({ $inc: { number: 1 } }, { $inc: { number: 1 } }, true), - ); + getTest({ $inc: { number: 1 } }, { $inc: { number: 1 } }, true) + ) it( 'when you clean a bad object it is now good', - getTest({ $inc: { number: 1, admin: 1 } }, { $inc: { number: 1 } }, true), - ); + getTest({ $inc: { number: 1, admin: 1 } }, { $inc: { number: 1 } }, true) + ) it( 'type conversion works', - getTest({ $inc: { number: '1' } }, { $inc: { number: 1 } }, true), - ); - }); + getTest({ $inc: { number: '1' } }, { $inc: { number: 1 } }, true) + ) + }) describe('$currentDate', function () { it( @@ -353,28 +353,28 @@ describe('clean', function () { getTest( { $currentDate: { date: true } }, { $currentDate: { date: true } }, - true, - ), - ); + true + ) + ) it( 'should not convert a $currentDate modifier with timestamp value', getTest( { $currentDate: { date: { $type: 'timestamp' } } }, { $currentDate: { date: { $type: 'timestamp' } } }, - true, - ), - ); + true + ) + ) it( 'should not convert a $currentDate modifier with date value', getTest( { $currentDate: { date: { $type: 'date' } } }, { $currentDate: { date: { $type: 'date' } } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$addToSet', function () { it( @@ -382,26 +382,26 @@ describe('clean', function () { getTest( { $addToSet: { allowedNumbersArray: 1 } }, { $addToSet: { allowedNumbersArray: 1 } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $addToSet: { allowedNumbersArray: 1, admin: 1 } }, { $addToSet: { allowedNumbersArray: 1 } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', getTest( { $addToSet: { allowedNumbersArray: '1' } }, { $addToSet: { allowedNumbersArray: 1 } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$addToSet with $each', function () { it( @@ -409,31 +409,31 @@ describe('clean', function () { getTest( { $addToSet: { allowedNumbersArray: { $each: [1, 2, 3] } } }, { $addToSet: { allowedNumbersArray: { $each: [1, 2, 3] } } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $addToSet: { allowedNumbersArray: { $each: [1, 2, 3] }, - admin: { $each: [1, 2, 3] }, - }, + admin: { $each: [1, 2, 3] } + } }, { $addToSet: { allowedNumbersArray: { $each: [1, 2, 3] } } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', getTest( { $addToSet: { allowedNumbersArray: { $each: ['1', 2, 3] } } }, { $addToSet: { allowedNumbersArray: { $each: [1, 2, 3] } } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$push', function () { it( @@ -441,26 +441,26 @@ describe('clean', function () { getTest( { $push: { allowedNumbersArray: 1 } }, { $push: { allowedNumbersArray: 1 } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $push: { allowedNumbersArray: 1, admin: 1 } }, { $push: { allowedNumbersArray: 1 } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', getTest( { $push: { allowedNumbersArray: '1' } }, { $push: { allowedNumbersArray: 1 } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$push with $each', function () { it( @@ -468,31 +468,31 @@ describe('clean', function () { getTest( { $push: { allowedNumbersArray: { $each: [1, 2, 3] } } }, { $push: { allowedNumbersArray: { $each: [1, 2, 3] } } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $push: { allowedNumbersArray: { $each: [1, 2, 3] }, - admin: { $each: [1, 2, 3] }, - }, + admin: { $each: [1, 2, 3] } + } }, { $push: { allowedNumbersArray: { $each: [1, 2, 3] } } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', getTest( { $push: { allowedNumbersArray: { $each: ['1', 2, 3] } } }, { $push: { allowedNumbersArray: { $each: [1, 2, 3] } } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$pull', function () { it( @@ -500,34 +500,34 @@ describe('clean', function () { getTest( { $pull: { allowedNumbersArray: 1 } }, { $pull: { allowedNumbersArray: 1 } }, - true, - ), - ); + true + ) + ) it( 'when you clean a good object with defaultValue it is still good', getTest( { $pull: { objectArray: { boolean: true } } }, { $pull: { objectArray: { boolean: true } } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $pull: { allowedNumbersArray: 1, admin: 1 } }, { $pull: { allowedNumbersArray: 1 } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', getTest( { $pull: { allowedNumbersArray: '1' } }, { $pull: { allowedNumbersArray: 1 } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$pull with query2', function () { it( @@ -535,34 +535,34 @@ describe('clean', function () { getTest( { $pull: { allowedNumbersArray: { $in: [1] } } }, { $pull: { allowedNumbersArray: { $in: [1] } } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $pull: { allowedNumbersArray: { $in: [1] }, admin: { $in: [1] } } }, { $pull: { allowedNumbersArray: { $in: [1] } } }, - true, - ), - ); + true + ) + ) it( 'type conversion does not work within query2', getTest( { $pull: { allowedNumbersArray: { $in: ['1'] } } }, { $pull: { allowedNumbersArray: { $in: ['1'] } } }, - true, - ), - ); + true + ) + ) it( 'more tests', getTest( { $pull: { allowedNumbersArray: { foo: { $in: [1] } } } }, { $pull: { allowedNumbersArray: { foo: { $in: [1] } } } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$pop', function () { it( @@ -570,26 +570,26 @@ describe('clean', function () { getTest( { $pop: { allowedNumbersArray: 1 } }, { $pop: { allowedNumbersArray: 1 } }, - true, - ), - ); + true + ) + ) it( 'when you clean a bad object it is now good', getTest( { $pop: { allowedNumbersArray: 1, admin: 1 } }, { $pop: { allowedNumbersArray: 1 } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', getTest( { $pop: { allowedNumbersArray: '1' } }, { $pop: { allowedNumbersArray: 1 } }, - true, - ), - ); - }); + true + ) + ) + }) describe('$pullAll', function () { it( @@ -597,103 +597,103 @@ describe('clean', function () { getTest( { $pullAll: { allowedNumbersArray: [1, 2, 3] } }, { $pullAll: { allowedNumbersArray: [1, 2, 3] } }, - true, - ), - ); + true + ) + ) it( 'type conversion works', getTest( { $pullAll: { allowedNumbersArray: ['1', 2, 3] } }, { $pullAll: { allowedNumbersArray: [1, 2, 3] } }, - true, - ), - ); - }); + true + ) + ) + }) describe('blackbox', function () { // Cleaning shouldn't remove anything within blackbox it( '1', - getTest({ blackBoxObject: { foo: 1 } }, { blackBoxObject: { foo: 1 } }), - ); + getTest({ blackBoxObject: { foo: 1 } }, { blackBoxObject: { foo: 1 } }) + ) it( '2', getTest( { blackBoxObject: { foo: [1] } }, - { blackBoxObject: { foo: [1] } }, - ), - ); + { blackBoxObject: { foo: [1] } } + ) + ) it( '3', getTest( { blackBoxObject: { foo: [{ bar: 1 }] } }, - { blackBoxObject: { foo: [{ bar: 1 }] } }, - ), - ); + { blackBoxObject: { foo: [{ bar: 1 }] } } + ) + ) it( '4', getTest( { $set: { blackBoxObject: { foo: 1 } } }, { $set: { blackBoxObject: { foo: 1 } } }, - true, - ), - ); + true + ) + ) it( '5', getTest( { $set: { blackBoxObject: { foo: [1] } } }, { $set: { blackBoxObject: { foo: [1] } } }, - true, - ), - ); + true + ) + ) it( '6', getTest( { $set: { blackBoxObject: { foo: [{ bar: 1 }] } } }, { $set: { blackBoxObject: { foo: [{ bar: 1 }] } } }, - true, - ), - ); + true + ) + ) it( '7', getTest( { $set: { - 'blackBoxObject.email.verificationTokens.$': { token: 'Hi' }, - }, + 'blackBoxObject.email.verificationTokens.$': { token: 'Hi' } + } }, { $set: { - 'blackBoxObject.email.verificationTokens.$': { token: 'Hi' }, - }, + 'blackBoxObject.email.verificationTokens.$': { token: 'Hi' } + } }, - true, - ), - ); + true + ) + ) it( '8', getTest( { $set: { 'blackBoxObject.email.verificationTokens.$.token': 'Hi' } }, { $set: { 'blackBoxObject.email.verificationTokens.$.token': 'Hi' } }, - true, - ), - ); + true + ) + ) it( '9', getTest( { - $push: { 'blackBoxObject.email.verificationTokens': { token: 'Hi' } }, + $push: { 'blackBoxObject.email.verificationTokens': { token: 'Hi' } } }, { - $push: { 'blackBoxObject.email.verificationTokens': { token: 'Hi' } }, + $push: { 'blackBoxObject.email.verificationTokens': { token: 'Hi' } } }, - true, - ), - ); - }); + true + ) + ) + }) it('trim strings', async function () { - async function doTest(isModifier, given, expected) { + async function doTest (isModifier, given, expected) { const cleanObj = await ss.clean(given, { mutate: true, filter: false, @@ -701,66 +701,66 @@ describe('clean', function () { removeEmptyStrings: false, trimStrings: true, getAutoValues: false, - isModifier, - }); - expect(cleanObj).to.deep.equal(expected); + isModifier + }) + expect(cleanObj).to.deep.equal(expected) } // DOC - await doTest(false, { string: ' This is a string ' }, { string: 'This is a string' }); + await doTest(false, { string: ' This is a string ' }, { string: 'This is a string' }) // $SET - await doTest(true, { $set: { string: ' This is a string ' } }, { $set: { string: 'This is a string' } }); + await doTest(true, { $set: { string: ' This is a string ' } }, { $set: { string: 'This is a string' } }) // $UNSET is ignored - await doTest(true, { $unset: { string: ' This is a string ' } }, { $unset: { string: ' This is a string ' } }); + await doTest(true, { $unset: { string: ' This is a string ' } }, { $unset: { string: ' This is a string ' } }) // $SETONINSERT - await doTest(true, { $setOnInsert: { string: ' This is a string ' } }, { $setOnInsert: { string: 'This is a string' } }); + await doTest(true, { $setOnInsert: { string: ' This is a string ' } }, { $setOnInsert: { string: 'This is a string' } }) // $ADDTOSET await doTest( true, { $addToSet: { minMaxStringArray: ' This is a string ' } }, - { $addToSet: { minMaxStringArray: 'This is a string' } }, - ); + { $addToSet: { minMaxStringArray: 'This is a string' } } + ) // $ADDTOSET WITH EACH await doTest( true, { $addToSet: { - minMaxStringArray: { $each: [' This is a string '] }, - }, + minMaxStringArray: { $each: [' This is a string '] } + } }, - { $addToSet: { minMaxStringArray: { $each: ['This is a string'] } } }, - ); + { $addToSet: { minMaxStringArray: { $each: ['This is a string'] } } } + ) // $PUSH - await doTest(true, { $push: { minMaxStringArray: ' This is a string ' } }, { $push: { minMaxStringArray: 'This is a string' } }); + await doTest(true, { $push: { minMaxStringArray: ' This is a string ' } }, { $push: { minMaxStringArray: 'This is a string' } }) // $PUSH WITH EACH await doTest( true, { $push: { minMaxStringArray: { $each: [' This is a string '] } } }, - { $push: { minMaxStringArray: { $each: ['This is a string'] } } }, - ); + { $push: { minMaxStringArray: { $each: ['This is a string'] } } } + ) // $PULL - await doTest(true, { $pull: { minMaxStringArray: ' This is a string ' } }, { $pull: { minMaxStringArray: 'This is a string' } }); + await doTest(true, { $pull: { minMaxStringArray: ' This is a string ' } }, { $pull: { minMaxStringArray: 'This is a string' } }) // $POP - await doTest(true, { $pop: { minMaxStringArray: ' This is a string ' } }, { $pop: { minMaxStringArray: 'This is a string' } }); + await doTest(true, { $pop: { minMaxStringArray: ' This is a string ' } }, { $pop: { minMaxStringArray: 'This is a string' } }) // $PULLALL await doTest( true, { $pullAll: { minMaxStringArray: [' This is a string '] } }, - { $pullAll: { minMaxStringArray: ['This is a string'] } }, - ); + { $pullAll: { minMaxStringArray: ['This is a string'] } } + ) // Trim false - await doTest(false, { noTrimString: ' This is a string ' }, { noTrimString: ' This is a string ' }); + await doTest(false, { noTrimString: ' This is a string ' }, { noTrimString: ' This is a string ' }) // Trim false with autoConvert const cleanObj = await ss.clean( @@ -771,295 +771,295 @@ describe('clean', function () { removeEmptyStrings: false, trimStrings: true, getAutoValues: false, - isModifier: false, - }, - ); - expect(cleanObj).to.deep.equal({ noTrimString: ' This is a string ' }); - }); + isModifier: false + } + ) + expect(cleanObj).to.deep.equal({ noTrimString: ' This is a string ' }) + }) describe('miscellaneous', function () { it('does not $unset when the prop is within an object that is already being $set', async function () { const optionalInObject = new SimpleSchema({ requiredObj: { - type: Object, + type: Object }, 'requiredObj.optionalProp': { type: String, - optional: true, + optional: true }, 'requiredObj.requiredProp': { - type: String, - }, - }); + type: String + } + }) const myObj = { - $set: { requiredObj: { requiredProp: 'blah', optionalProp: '' } }, - }; - await optionalInObject.clean(myObj, { isModifier: true, mutate: true }); + $set: { requiredObj: { requiredProp: 'blah', optionalProp: '' } } + } + await optionalInObject.clean(myObj, { isModifier: true, mutate: true }) expect(myObj).to.deep.equal({ - $set: { requiredObj: { requiredProp: 'blah' } }, - }); - }); + $set: { requiredObj: { requiredProp: 'blah' } } + }) + }) it('type convert to array', async function () { - const myObj1 = { allowedStringsArray: 'tuna' }; - await ss.clean(myObj1, { mutate: true }); - expect(myObj1).to.deep.equal({ allowedStringsArray: ['tuna'] }); + const myObj1 = { allowedStringsArray: 'tuna' } + await ss.clean(myObj1, { mutate: true }) + expect(myObj1).to.deep.equal({ allowedStringsArray: ['tuna'] }) - const myObj2 = { $set: { allowedStringsArray: 'tuna' } }; - await ss.clean(myObj2, { isModifier: true, mutate: true }); - expect(myObj2).to.deep.equal({ $set: { allowedStringsArray: ['tuna'] } }); - }); + const myObj2 = { $set: { allowedStringsArray: 'tuna' } } + await ss.clean(myObj2, { isModifier: true, mutate: true }) + expect(myObj2).to.deep.equal({ $set: { allowedStringsArray: ['tuna'] } }) + }) it('multi-dimensional arrays', async function () { const schema = new SimpleSchema({ geometry: { type: Object, - optional: true, + optional: true }, 'geometry.coordinates': { - type: Array, + type: Array }, 'geometry.coordinates.$': { - type: Array, + type: Array }, 'geometry.coordinates.$.$': { - type: Array, + type: Array }, 'geometry.coordinates.$.$.$': { - type: SimpleSchema.Integer, - }, - }); + type: SimpleSchema.Integer + } + }) const doc = { geometry: { - coordinates: [[[30, 50]]], - }, - }; + coordinates: [[[30, 50]]] + } + } - const expected = JSON.stringify(doc); - expect(JSON.stringify(await schema.clean(doc))).to.deep.equal(expected); - }); + const expected = JSON.stringify(doc) + expect(JSON.stringify(await schema.clean(doc))).to.deep.equal(expected) + }) it('removeNullsFromArrays removes nulls from arrays', async function () { const schema = new SimpleSchema({ names: Array, - 'names.$': String, - }); + 'names.$': String + }) const cleanedObject = await schema.clean( { - names: [null, 'foo', null], + names: [null, 'foo', null] }, - { removeNullsFromArrays: true }, - ); + { removeNullsFromArrays: true } + ) expect(cleanedObject).to.deep.equal({ - names: ['foo'], - }); - }); + names: ['foo'] + }) + }) it('removeNullsFromArrays does not remove non-null objects from arrays', async function () { const schema = new SimpleSchema({ a: Array, 'a.$': Object, - 'a.$.b': Number, - }); + 'a.$.b': Number + }) const cleanedObject = await schema.clean( { $set: { - a: [{ b: 1 }], - }, + a: [{ b: 1 }] + } }, - { removeNullsFromArrays: true }, - ); + { removeNullsFromArrays: true } + ) // Should be unchanged expect(cleanedObject).to.deep.equal({ $set: { - a: [{ b: 1 }], - }, - }); - }); + a: [{ b: 1 }] + } + }) + }) it('remove object', async function () { const schema = new SimpleSchema({ names: { type: Array }, - 'names.$': { type: String }, - }); + 'names.$': { type: String } + }) const doc = { - names: [{ hello: 'world' }], - }; - await schema.clean(doc, { mutate: true }); + names: [{ hello: 'world' }] + } + await schema.clean(doc, { mutate: true }) expect(doc).to.deep.equal({ - names: [], - }); - }); - }); + names: [] + }) + }) + }) it('should clean sub schemas', async function () { const doubleNestedSchema = new SimpleSchema({ - integer: SimpleSchema.Integer, - }); + integer: SimpleSchema.Integer + }) const nestedSchema = new SimpleSchema({ - doubleNested: doubleNestedSchema, - }); + doubleNested: doubleNestedSchema + }) const schema = new SimpleSchema({ nested: Array, - 'nested.$': nestedSchema, - }); + 'nested.$': nestedSchema + }) const cleanedObject = await schema.clean({ nested: [ { doubleNested: { - integer: '1', - }, - }, - ], - }); + integer: '1' + } + } + ] + }) expect(cleanedObject).to.deep.equal({ nested: [ { doubleNested: { - integer: 1, - }, - }, - ], - }); - }); + integer: 1 + } + } + ] + }) + }) describe('with SimpleSchema.oneOf(String, Number, Date)', async function () { const oneOfSchema = new SimpleSchema({ field: { - type: SimpleSchema.oneOf(String, Number, Date), + type: SimpleSchema.oneOf(String, Number, Date) }, nested: { - type: Object, + type: Object }, - 'nested.field': SimpleSchema.oneOf(String, Number, Date), - }); + 'nested.field': SimpleSchema.oneOf(String, Number, Date) + }) - async function doTest(given, expected) { - const cleanObj = await oneOfSchema.clean(given, { mutate: true }); - expect(cleanObj).to.deep.equal(expected); + async function doTest (given, expected) { + const cleanObj = await oneOfSchema.clean(given, { mutate: true }) + expect(cleanObj).to.deep.equal(expected) } it('should not convert a string', async function () { - await doTest({ field: 'I am a string' }, { field: 'I am a string' }); - }); + await doTest({ field: 'I am a string' }, { field: 'I am a string' }) + }) it('should not convert a number', async function () { - await doTest({ field: 12345 }, { field: 12345 }); - }); + await doTest({ field: 12345 }, { field: 12345 }) + }) it('should not convert a Date', async function () { - await doTest({ field: new Date(12345) }, { field: new Date(12345) }); - }); + await doTest({ field: new Date(12345) }, { field: new Date(12345) }) + }) it('should convert a Date if no Date in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { - type: SimpleSchema.oneOf(String, Number), - }, - }); - const date = new Date(12345); - const dateStrng = date.toString(); - - const cleanObj = await schemaNoDate.clean({ field: date }, { mutate: true }); - expect(cleanObj).to.deep.equal({ field: dateStrng }); - }); + type: SimpleSchema.oneOf(String, Number) + } + }) + const date = new Date(12345) + const dateStrng = date.toString() + + const cleanObj = await schemaNoDate.clean({ field: date }, { mutate: true }) + expect(cleanObj).to.deep.equal({ field: dateStrng }) + }) it('should convert a String if no String in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { - type: SimpleSchema.oneOf(Number, Date), - }, - }); + type: SimpleSchema.oneOf(Number, Date) + } + }) - const cleanObj = await schemaNoDate.clean({ field: '12345' }, { mutate: true }); - expect(cleanObj).to.deep.equal({ field: 12345 }); - }); + const cleanObj = await schemaNoDate.clean({ field: '12345' }, { mutate: true }) + expect(cleanObj).to.deep.equal({ field: 12345 }) + }) it('should convert a Number if no Number in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { - type: SimpleSchema.oneOf(String, Date), - }, - }); + type: SimpleSchema.oneOf(String, Date) + } + }) - const cleanObj = await schemaNoDate.clean({ field: 12345 }, { mutate: true }); - expect(cleanObj).to.deep.equal({ field: '12345' }); - }); + const cleanObj = await schemaNoDate.clean({ field: 12345 }, { mutate: true }) + expect(cleanObj).to.deep.equal({ field: '12345' }) + }) describe('with modifiers', function () { it('should not convert a string', async function () { - await doTest({ $set: { field: 'I am a string' } }, { $set: { field: 'I am a string' } }); - }); + await doTest({ $set: { field: 'I am a string' } }, { $set: { field: 'I am a string' } }) + }) it('should not convert a nested string', async function () { - await doTest({ $set: { field: 'I am a string' } }, { $set: { field: 'I am a string' } }); - }); + await doTest({ $set: { field: 'I am a string' } }, { $set: { field: 'I am a string' } }) + }) it('should not convert a number', async function () { - await doTest({ $set: { field: 12345 } }, { $set: { field: 12345 } }); - }); + await doTest({ $set: { field: 12345 } }, { $set: { field: 12345 } }) + }) it('should not convert a Date', async function () { - await doTest({ $set: { field: new Date(12345) } }, { $set: { field: new Date(12345) } }); - }); + await doTest({ $set: { field: new Date(12345) } }, { $set: { field: new Date(12345) } }) + }) describe('nested operator', function () { it('should not convert a string', async function () { - await doTest({ $set: { 'nested.field': 'I am a string' } }, { $set: { 'nested.field': 'I am a string' } }); - }); + await doTest({ $set: { 'nested.field': 'I am a string' } }, { $set: { 'nested.field': 'I am a string' } }) + }) it('should not convert a nested string', async function () { - await doTest({ $set: { 'nested.field': 'I am a string' } }, { $set: { 'nested.field': 'I am a string' } }); - }); + await doTest({ $set: { 'nested.field': 'I am a string' } }, { $set: { 'nested.field': 'I am a string' } }) + }) it('should not convert a number', async function () { - await doTest({ $set: { 'nested.field': 12345 } }, { $set: { 'nested.field': 12345 } }); - }); + await doTest({ $set: { 'nested.field': 12345 } }, { $set: { 'nested.field': 12345 } }) + }) it('should not convert a Date', async function () { - await doTest({ $set: { 'nested.field': new Date(12345) } }, { $set: { 'nested.field': new Date(12345) } }); - }); - }); + await doTest({ $set: { 'nested.field': new Date(12345) } }, { $set: { 'nested.field': new Date(12345) } }) + }) + }) it('should convert a Date if no Date in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { - type: SimpleSchema.oneOf(String, Number), - }, - }); - const date = new Date(12345); - const dateString = date.toString(); + type: SimpleSchema.oneOf(String, Number) + } + }) + const date = new Date(12345) + const dateString = date.toString() - const cleanObj = await schemaNoDate.clean({ $set: { field: date } }, { mutate: true }); - expect(cleanObj).to.deep.equal({ $set: { field: dateString } }); - }); + const cleanObj = await schemaNoDate.clean({ $set: { field: date } }, { mutate: true }) + expect(cleanObj).to.deep.equal({ $set: { field: dateString } }) + }) it('should convert a String if no String in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { - type: SimpleSchema.oneOf(Number, Date), - }, - }); + type: SimpleSchema.oneOf(Number, Date) + } + }) - const cleanObj = await schemaNoDate.clean({ $set: { field: '12345' } }, { mutate: true }); - expect(cleanObj).to.deep.equal({ $set: { field: 12345 } }); - }); + const cleanObj = await schemaNoDate.clean({ $set: { field: '12345' } }, { mutate: true }) + expect(cleanObj).to.deep.equal({ $set: { field: 12345 } }) + }) it('should convert a Number if no Number in oneOf', async function () { const schemaNoDate = new SimpleSchema({ field: { - type: SimpleSchema.oneOf(String, Date), - }, - }); - - const cleanObj = await schemaNoDate.clean({ $set: { field: 12345 } }, { mutate: true }); - expect(cleanObj).to.deep.equal({ $set: { field: '12345' } }); - }); - }); - }); -}); + type: SimpleSchema.oneOf(String, Date) + } + }) + + const cleanObj = await schemaNoDate.clean({ $set: { field: 12345 } }, { mutate: true }) + expect(cleanObj).to.deep.equal({ $set: { field: '12345' } }) + }) + }) + }) +}) diff --git a/lib/clean/AutoValueRunner.js b/lib/clean/AutoValueRunner.js index 781cbf7..e88632d 100644 --- a/lib/clean/AutoValueRunner.js +++ b/lib/clean/AutoValueRunner.js @@ -1,26 +1,26 @@ -import clone from 'clone'; -import { getParentOfKey } from '../utility'; +import clone from 'clone' +import { getParentOfKey } from '../utility' -function getFieldInfo(mongoObject, key) { - const keyInfo = mongoObject.getInfoForKey(key) || {}; +function getFieldInfo (mongoObject, key) { + const keyInfo = mongoObject.getInfoForKey(key) || {} return { isSet: (keyInfo.value !== undefined), value: keyInfo.value, - operator: keyInfo.operator || null, - }; + operator: keyInfo.operator || null + } } export default class AutoValueRunner { - constructor(options) { - this.options = options; - this.doneKeys = []; + constructor (options) { + this.options = options + this.doneKeys = [] } - async runForPosition({ + async runForPosition ({ key: affectedKey, operator, position, - value, + value }) { const { closestSubschemaFieldName, @@ -28,64 +28,64 @@ export default class AutoValueRunner { func, isModifier, isUpsert, - mongoObject, - } = this.options; + mongoObject + } = this.options // If already called for this key, skip it - if (this.doneKeys.includes(affectedKey)) return; + if (this.doneKeys.includes(affectedKey)) return - const fieldParentName = getParentOfKey(affectedKey, true); - const parentFieldInfo = getFieldInfo(mongoObject, fieldParentName.slice(0, -1)); + const fieldParentName = getParentOfKey(affectedKey, true) + const parentFieldInfo = getFieldInfo(mongoObject, fieldParentName.slice(0, -1)) - let doUnset = false; + let doUnset = false if (Array.isArray(parentFieldInfo.value)) { if (isNaN(affectedKey.split('.').slice(-1).pop())) { // parent is an array, but the key to be set is not an integer (see issue #80) - return; + return } } const autoValue = await func.call({ closestSubschemaFieldName: closestSubschemaFieldName.length ? closestSubschemaFieldName : null, - field(fName) { - return getFieldInfo(mongoObject, closestSubschemaFieldName + fName); + field (fName) { + return getFieldInfo(mongoObject, closestSubschemaFieldName + fName) }, isModifier, isUpsert, isSet: (value !== undefined), key: affectedKey, operator, - parentField() { - return parentFieldInfo; + parentField () { + return parentFieldInfo }, - siblingField(fName) { - return getFieldInfo(mongoObject, fieldParentName + fName); + siblingField (fName) { + return getFieldInfo(mongoObject, fieldParentName + fName) }, - unset() { - doUnset = true; + unset () { + doUnset = true }, value, - ...(extendedAutoValueContext || {}), - }, mongoObject.getObject()); + ...(extendedAutoValueContext || {}) + }, mongoObject.getObject()) // Update tracking of which keys we've run autovalue for - this.doneKeys.push(affectedKey); + this.doneKeys.push(affectedKey) - if (doUnset && position) mongoObject.removeValueForPosition(position); + if (doUnset && position) mongoObject.removeValueForPosition(position) - if (autoValue === undefined) return; + if (autoValue === undefined) return // If the user's auto value is of the pseudo-modifier format, parse it // into operator and value. if (isModifier) { - let op; - let newValue; + let op + let newValue if (autoValue && typeof autoValue === 'object') { - const avOperator = Object.keys(autoValue).find((avProp) => avProp.substring(0, 1) === '$'); + const avOperator = Object.keys(autoValue).find((avProp) => avProp.substring(0, 1) === '$') if (avOperator) { - op = avOperator; - newValue = autoValue[avOperator]; + op = avOperator + newValue = autoValue[avOperator] } } @@ -93,20 +93,20 @@ export default class AutoValueRunner { // above the "if (op)" block below since we might change op // in this line. if (!op && position.slice(0, 1) !== '$') { - op = '$set'; - newValue = autoValue; + op = '$set' + newValue = autoValue } if (op) { // Update/change value - mongoObject.removeValueForPosition(position); - mongoObject.setValueForPosition(`${op}[${affectedKey}]`, clone(newValue)); - return; + mongoObject.removeValueForPosition(position) + mongoObject.setValueForPosition(`${op}[${affectedKey}]`, clone(newValue)) + return } } // Update/change value. Cloning is necessary in case it's an object, because // if we later set some keys within it, they'd be set on the original object, too. - mongoObject.setValueForPosition(position, clone(autoValue)); + mongoObject.setValueForPosition(position, clone(autoValue)) } } diff --git a/lib/clean/autoValue.tests.js b/lib/clean/autoValue.tests.js index 272e5c7..a2a7dfe 100644 --- a/lib/clean/autoValue.tests.js +++ b/lib/clean/autoValue.tests.js @@ -1,7 +1,7 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from '../SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from '../SimpleSchema' describe('autoValue', function () { describe('has correct information in function context', function () { @@ -9,695 +9,695 @@ describe('autoValue', function () { const schema = new SimpleSchema({ foo: { type: String, - optional: true, + optional: true }, bar: { type: Boolean, optional: true, - autoValue() { - expect(this.key).to.equal('bar'); - expect(this.closestSubschemaFieldName).to.equal(null); - expect(this.isSet).to.equal(false); - expect(this.value).to.equal(undefined); - expect(this.operator).to.equal(null); - - const foo = this.field('foo'); + autoValue () { + expect(this.key).to.equal('bar') + expect(this.closestSubschemaFieldName).to.equal(null) + expect(this.isSet).to.equal(false) + expect(this.value).to.equal(undefined) + expect(this.operator).to.equal(null) + + const foo = this.field('foo') expect(foo).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - const fooSibling = this.siblingField('foo'); + const fooSibling = this.siblingField('foo') expect(fooSibling).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - const fooParent = this.parentField(); + const fooParent = this.parentField() expect(fooParent).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); - }, - }, - }); - await schema.clean({}); - }); + value: undefined + }) + } + } + }) + await schema.clean({}) + }) it('normal other key', async function () { const schema = new SimpleSchema({ foo: { type: String, - optional: true, + optional: true }, bar: { type: Boolean, optional: true, - autoValue() { - expect(this.isSet).to.equal(false); - expect(this.value).to.equal(undefined); - expect(this.operator).to.equal(null); + autoValue () { + expect(this.isSet).to.equal(false) + expect(this.value).to.equal(undefined) + expect(this.operator).to.equal(null) - const foo = this.field('foo'); + const foo = this.field('foo') expect(foo).to.deep.equal({ isSet: true, operator: null, - value: 'clown', - }); + value: 'clown' + }) - const fooSibling = this.siblingField('foo'); + const fooSibling = this.siblingField('foo') expect(fooSibling).to.deep.equal({ isSet: true, operator: null, - value: 'clown', - }); + value: 'clown' + }) - const fooParent = this.parentField(); + const fooParent = this.parentField() expect(fooParent).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); - }, - }, - }); + value: undefined + }) + } + } + }) await schema.clean({ - foo: 'clown', - }); - }); + foo: 'clown' + }) + }) it('normal self and other key', async function () { const schema = new SimpleSchema({ foo: { type: String, - optional: true, + optional: true }, bar: { type: Boolean, optional: true, - autoValue() { - expect(this.isSet).to.equal(true); - expect(this.value).to.equal(true); - expect(this.operator).to.equal(null); + autoValue () { + expect(this.isSet).to.equal(true) + expect(this.value).to.equal(true) + expect(this.operator).to.equal(null) - const foo = this.field('foo'); + const foo = this.field('foo') expect(foo).to.deep.equal({ isSet: true, operator: null, - value: 'clown', - }); + value: 'clown' + }) - const fooSibling = this.siblingField('foo'); + const fooSibling = this.siblingField('foo') expect(fooSibling).to.deep.equal({ isSet: true, operator: null, - value: 'clown', - }); + value: 'clown' + }) - const fooParent = this.parentField(); + const fooParent = this.parentField() expect(fooParent).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); - }, - }, - }); + value: undefined + }) + } + } + }) await schema.clean({ foo: 'clown', - bar: true, - }); - }); + bar: true + }) + }) it('parentField', async function () { const schema = new SimpleSchema({ foo: { type: Object, - optional: true, + optional: true }, 'foo.bar': { type: Boolean, optional: true, - autoValue() { + autoValue () { expect(this.parentField()).to.deep.equal({ isSet: true, operator: null, - value: {}, - }); - }, - }, - }); + value: {} + }) + } + } + }) await schema.clean({ - foo: {}, - }); - }); + foo: {} + }) + }) it('closestSubschemaFieldName set', async function () { const schema1 = new SimpleSchema({ dug: { type: Boolean, optional: true, - autoValue() { - expect(this.key).to.equal('dig.dug'); - expect(this.closestSubschemaFieldName).to.equal('dig'); - }, - }, - }); + autoValue () { + expect(this.key).to.equal('dig.dug') + expect(this.closestSubschemaFieldName).to.equal('dig') + } + } + }) const schema2 = new SimpleSchema({ dig: { type: schema1, - optional: true, - }, - }); + optional: true + } + }) await schema2.clean({ - dig: {}, - }); - }); + dig: {} + }) + }) it('normal self and no other key with unset', async function () { const schema = new SimpleSchema({ foo: { type: String, - optional: true, + optional: true }, bar: { type: Boolean, optional: true, - autoValue() { - expect(this.isSet).to.equal(true); - expect(this.value).to.equal(false); - expect(this.operator).to.equal(null); + autoValue () { + expect(this.isSet).to.equal(true) + expect(this.value).to.equal(false) + expect(this.operator).to.equal(null) - const foo = this.field('foo'); + const foo = this.field('foo') expect(foo).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - const fooSibling = this.siblingField('foo'); + const fooSibling = this.siblingField('foo') expect(fooSibling).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - const fooParent = this.parentField(); + const fooParent = this.parentField() expect(fooParent).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - this.unset(); - }, - }, - }); + this.unset() + } + } + }) const doc = { - bar: false, - }; - expect(await schema.clean(doc)).to.deep.equal({}); - }); + bar: false + } + expect(await schema.clean(doc)).to.deep.equal({}) + }) it('$set self and no other key', async function () { const schema = new SimpleSchema({ foo: { type: String, - optional: true, + optional: true }, bar: { type: Boolean, optional: true, - autoValue() { - expect(this.isSet).to.equal(true); - expect(this.value).to.equal(false); - expect(this.operator).to.equal('$set'); + autoValue () { + expect(this.isSet).to.equal(true) + expect(this.value).to.equal(false) + expect(this.operator).to.equal('$set') - const foo = this.field('foo'); + const foo = this.field('foo') expect(foo).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - const fooSibling = this.siblingField('foo'); + const fooSibling = this.siblingField('foo') expect(fooSibling).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - const fooParent = this.parentField(); + const fooParent = this.parentField() expect(fooParent).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); - }, - }, - }); + value: undefined + }) + } + } + }) const doc = { $set: { - bar: false, - }, - }; - await schema.clean(doc); + bar: false + } + } + await schema.clean(doc) expect(doc).to.deep.equal({ $set: { - bar: false, - }, - }); - }); + bar: false + } + }) + }) it('$set self and another key and change self', async function () { const schema = new SimpleSchema({ foo: { type: String, - optional: true, + optional: true }, bar: { type: Boolean, optional: true, - autoValue() { - expect(this.isSet).to.equal(true); - expect(this.value).to.equal(false); - expect(this.operator).to.equal('$set'); + autoValue () { + expect(this.isSet).to.equal(true) + expect(this.value).to.equal(false) + expect(this.operator).to.equal('$set') - const foo = this.field('foo'); + const foo = this.field('foo') expect(foo).to.deep.equal({ isSet: true, operator: '$set', - value: 'clown', - }); + value: 'clown' + }) - const fooSibling = this.siblingField('foo'); + const fooSibling = this.siblingField('foo') expect(fooSibling).to.deep.equal({ isSet: true, operator: '$set', - value: 'clown', - }); + value: 'clown' + }) - const fooParent = this.parentField(); + const fooParent = this.parentField() expect(fooParent).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - return true; - }, - }, - }); + return true + } + } + }) const doc = { $set: { foo: 'clown', - bar: false, - }, - }; + bar: false + } + } expect(await schema.clean(doc)).to.deep.equal({ $set: { foo: 'clown', - bar: true, - }, - }); - }); + bar: true + } + }) + }) it('adds $set when missing', async function () { const schema = new SimpleSchema({ foo: { type: String, - optional: true, + optional: true }, bar: { type: Boolean, optional: true, - autoValue() { - expect(this.isSet).to.equal(false); - expect(this.value).to.equal(undefined); - expect(this.operator).to.equal('$set'); + autoValue () { + expect(this.isSet).to.equal(false) + expect(this.value).to.equal(undefined) + expect(this.operator).to.equal('$set') - const foo = this.field('foo'); + const foo = this.field('foo') expect(foo).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - const fooSibling = this.siblingField('foo'); + const fooSibling = this.siblingField('foo') expect(fooSibling).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) - const fooParent = this.parentField(); + const fooParent = this.parentField() expect(fooParent).to.deep.equal({ isSet: false, operator: null, - value: undefined, - }); + value: undefined + }) return { - $set: true, - }; - }, - }, - }); + $set: true + } + } + } + }) expect(await schema.clean({}, { isModifier: true })).to.deep.equal({ $set: { - bar: true, - }, - }); - }); - }); + bar: true + } + }) + }) + }) it('content autoValues', async function () { const schema = new SimpleSchema({ content: { type: String, - optional: true, + optional: true }, updatesHistory: { type: Array, optional: true, - autoValue() { - const content = this.field('content'); + autoValue () { + const content = this.field('content') if (content.isSet) { if (!this.operator) { return [{ date: new Date('2017-01-01T00:00:00.000Z'), - content: content.value, - }]; + content: content.value + }] } return { $push: { date: new Date('2017-01-01T00:00:00.000Z'), - content: content.value, - }, - }; + content: content.value + } + } } - }, + } }, 'updatesHistory.$': { - type: Object, + type: Object }, 'updatesHistory.$.content': { type: String, - optional: true, - }, - }); + optional: true + } + }) // Normal object - let result = await schema.clean({ content: 'foo' }); + let result = await schema.clean({ content: 'foo' }) expect(result).to.deep.equal({ content: 'foo', updatesHistory: [ { date: new Date('2017-01-01T00:00:00.000Z'), - content: 'foo', - }, - ], - }); + content: 'foo' + } + ] + }) // $set - result = await schema.clean({ $set: { content: 'foo' } }); + result = await schema.clean({ $set: { content: 'foo' } }) expect(result).to.deep.equal({ $set: { - content: 'foo', + content: 'foo' }, $push: { updatesHistory: { date: new Date('2017-01-01T00:00:00.000Z'), - content: 'foo', - }, - }, - }); - }); + content: 'foo' + } + } + }) + }) - it('async content'); + it('async content') it('array of objects autoValues', async function () { const schema = new SimpleSchema({ avArrayOfObjects: { type: Array, - optional: true, + optional: true }, 'avArrayOfObjects.$': { - type: Object, + type: Object }, 'avArrayOfObjects.$.a': { - type: String, + type: String }, 'avArrayOfObjects.$.foo': { type: String, - autoValue() { - return 'bar'; - }, - }, - }); + autoValue () { + return 'bar' + } + } + }) let result = await schema.clean({ $push: { avArrayOfObjects: { - a: 'b', - }, - }, - }); + a: 'b' + } + } + }) expect(result).to.deep.equal({ $push: { avArrayOfObjects: { a: 'b', - foo: 'bar', - }, - }, - }); + foo: 'bar' + } + } + }) result = await schema.clean({ $set: { avArrayOfObjects: [{ - a: 'b', + a: 'b' }, { - a: 'c', - }], - }, - }); + a: 'c' + }] + } + }) expect(result).to.deep.equal({ $set: { avArrayOfObjects: [{ a: 'b', - foo: 'bar', + foo: 'bar' }, { a: 'c', - foo: 'bar', - }], - }, - }); - }); + foo: 'bar' + }] + } + }) + }) - it('async array of objects autoValues'); + it('async array of objects autoValues') it('$each in autoValue pseudo modifier', async function () { const schema = new SimpleSchema({ psuedoEach: { type: Array, optional: true, - autoValue() { + autoValue () { if (this.isSet && this.operator === '$set') { return { $push: { - $each: this.value, - }, - }; + $each: this.value + } + } } - }, + } }, 'psuedoEach.$': { - type: String, - }, - }); + type: String + } + }) const result = await schema.clean({ $set: { - psuedoEach: ['foo', 'bar'], - }, - }); + psuedoEach: ['foo', 'bar'] + } + }) expect(result).to.deep.equal({ $push: { psuedoEach: { - $each: ['foo', 'bar'], - }, - }, - }); - }); + $each: ['foo', 'bar'] + } + } + }) + }) - it('async $each in autoValue pseudo modifier'); + it('async $each in autoValue pseudo modifier') it('simple autoValues', async function () { const schema = new SimpleSchema({ name: { - type: String, + type: String }, someDefault: { type: SimpleSchema.Integer, - autoValue() { - if (!this.isSet) return 5; - }, + autoValue () { + if (!this.isSet) return 5 + } }, updateCount: { type: SimpleSchema.Integer, - autoValue() { - if (!this.operator) return 0; - return { $inc: 1 }; - }, + autoValue () { + if (!this.operator) return 0 + return { $inc: 1 } + } }, firstWord: { type: String, optional: true, - autoValue() { - const content = this.field('content'); - if (content.isSet) return content.value.split(' ')[0]; - this.unset(); - }, - }, - }); + autoValue () { + const content = this.field('content') + if (content.isSet) return content.value.split(' ')[0] + this.unset() + } + } + }) let result = await schema.clean({ name: 'Test', - firstWord: 'Illegal to manually set value', - }); + firstWord: 'Illegal to manually set value' + }) expect(result).to.deep.equal({ name: 'Test', someDefault: 5, - updateCount: 0, - }); + updateCount: 0 + }) result = await schema.clean({ name: 'Test', - someDefault: 20, - }); + someDefault: 20 + }) expect(result).to.deep.equal({ name: 'Test', someDefault: 20, - updateCount: 0, - }); + updateCount: 0 + }) result = await schema.clean({ $set: { name: 'Test', - someDefault: 20, - }, - }); + someDefault: 20 + } + }) expect(result).to.deep.equal({ $set: { name: 'Test', - someDefault: 20, + someDefault: 20 }, - $inc: { updateCount: 1 }, - }); - }); + $inc: { updateCount: 1 } + }) + }) - it('async simple autoValues'); + it('async simple autoValues') it('objects in arrays', async function () { const subSchema = new SimpleSchema({ value: { type: String, - autoValue() { - expect(this.isSet).to.equal(true); - expect(this.operator).to.deep.equal('$set'); - expect(this.value).to.deep.equal('should be overridden by autovalue'); - return 'autovalue'; - }, - }, - }); + autoValue () { + expect(this.isSet).to.equal(true) + expect(this.operator).to.deep.equal('$set') + expect(this.value).to.deep.equal('should be overridden by autovalue') + return 'autovalue' + } + } + }) const schema = new SimpleSchema({ children: { - type: Array, + type: Array }, 'children.$': { - type: subSchema, - }, - }); + type: subSchema + } + }) const result = await schema.clean( { $set: { - 'children.$.value': 'should be overridden by autovalue', - }, + 'children.$.value': 'should be overridden by autovalue' + } }, - { isModifier: true }, - ); + { isModifier: true } + ) - expect(result.$set['children.$.value']).to.equal('autovalue'); - }); + expect(result.$set['children.$.value']).to.equal('autovalue') + }) it('operator correct for $pull', async function () { - let called = false; + let called = false const schema = new SimpleSchema({ foo: { type: Array, - autoValue() { - called = true; - expect(this.operator).to.deep.equal('$pull'); - }, + autoValue () { + called = true + expect(this.operator).to.deep.equal('$pull') + } }, 'foo.$': { - type: String, - }, - }); + type: String + } + }) await schema.clean({ $pull: { - foo: 'bar', - }, - }); + foo: 'bar' + } + }) - expect(called).to.equal(true); - }); + expect(called).to.equal(true) + }) it('issue 340', async function () { - let called = 0; + let called = 0 const schema = new SimpleSchema({ field1: { - type: SimpleSchema.Integer, + type: SimpleSchema.Integer }, field2: { type: String, - autoValue() { - called++; - expect(this.field('field1').value).to.equal(1); - expect(this.siblingField('field1').value).to.equal(1); - return 'foo'; - }, - }, - }); + autoValue () { + called++ + expect(this.field('field1').value).to.equal(1) + expect(this.siblingField('field1').value).to.equal(1) + return 'foo' + } + } + }) await schema.clean({ - field1: 1, - }); + field1: 1 + }) await schema.clean({ $set: { - field1: 1, - }, - }); + field1: 1 + } + }) - expect(called).to.equal(2); - }); + expect(called).to.equal(2) + }) it('should allow getting previous autoValue in later autoValue', async function () { const schema = new SimpleSchema( @@ -706,82 +706,82 @@ describe('autoValue', function () { tax: { type: Number, optional: true, - autoValue() { - return 0.5; - }, + autoValue () { + return 0.5 + } }, total: { type: Number, optional: true, - autoValue() { - const amount = this.field('amount').value || 0; - const tax = this.field('tax').value || 0; - return amount * (1 + tax); - }, - }, + autoValue () { + const amount = this.field('amount').value || 0 + const tax = this.field('tax').value || 0 + return amount * (1 + tax) + } + } }, { clean: { filter: false, - autoConvert: false, - }, - }, - ); + autoConvert: false + } + } + ) expect(await schema.clean({ amount: 1 })).to.deep.equal({ amount: 1, tax: 0.5, - total: 1.5, - }); - }); + total: 1.5 + }) + }) it('clean options should be merged when extending', async function () { const schema1 = new SimpleSchema( { - a: String, + a: String }, { clean: { filter: false, - autoConvert: false, - }, - }, - ); + autoConvert: false + } + } + ) - const schema2 = new SimpleSchema({}); - schema2.extend(schema1); + const schema2 = new SimpleSchema({}) + schema2.extend(schema1) - expect(await schema2.clean({ a: 1 })).to.deep.equal({ a: 1 }); - }); + expect(await schema2.clean({ a: 1 })).to.deep.equal({ a: 1 }) + }) it('array items', async function () { const schema = new SimpleSchema({ tags: { type: Array, - optional: true, + optional: true }, 'tags.$': { type: String, - autoValue() { - if (this.isSet) return this.value.toLowerCase(); - }, - }, - }); + autoValue () { + if (this.isSet) return this.value.toLowerCase() + } + } + }) const obj = { - tags: [], - }; + tags: [] + } expect(await schema.clean(obj)).to.deep.equal({ - tags: [], - }); + tags: [] + }) const obj2 = { - tags: ['FOO', 'BAR'], - }; + tags: ['FOO', 'BAR'] + } expect(await schema.clean(obj2)).to.deep.equal({ - tags: ['foo', 'bar'], - }); - }); + tags: ['foo', 'bar'] + }) + }) it('updates existing objects when deeply nested (plain)', async function () { const schema = new SimpleSchema({ @@ -790,42 +790,42 @@ describe('autoValue', function () { 'nested.$.doubleNested': Object, 'nested.$.doubleNested.integer': { type: SimpleSchema.Integer, - autoValue() { + autoValue () { if (!this.value) { - return 5; + return 5 } - }, - }, - }); + } + } + }) const cleanedObject = await schema.clean({ nested: [ { - doubleNested: {}, + doubleNested: {} }, { doubleNested: { - integer: '8', - }, - }, - ], - }); + integer: '8' + } + } + ] + }) expect(cleanedObject).to.deep.equal({ nested: [ { doubleNested: { - integer: 5, - }, + integer: 5 + } }, { doubleNested: { - integer: 8, - }, - }, - ], - }); - }); + integer: 8 + } + } + ] + }) + }) it('updates existing objects when deeply nested (modifier)', async function () { const schema = new SimpleSchema({ @@ -834,32 +834,32 @@ describe('autoValue', function () { 'nested.$.doubleNested': Object, 'nested.$.doubleNested.integer': { type: SimpleSchema.Integer, - autoValue() { + autoValue () { if (!this.value) { - return 5; + return 5 } - }, - }, - }); + } + } + }) const cleanedObject = await schema.clean({ $push: { nested: { - doubleNested: {}, - }, - }, - }); + doubleNested: {} + } + } + }) expect(cleanedObject).to.deep.equal({ $push: { nested: { doubleNested: { - integer: 5, - }, - }, - }, - }); - }); + integer: 5 + } + } + } + }) + }) it('updates deeply nested with empty $set', async function () { const schema = new SimpleSchema({ @@ -867,40 +867,40 @@ describe('autoValue', function () { 'nested.$': Object, 'nested.$.doubleNested': { type: Object, - autoValue() { + autoValue () { if (!this.value) { - return {}; + return {} } - }, + } }, 'nested.$.doubleNested.integer': { type: SimpleSchema.Integer, - autoValue() { + autoValue () { if (!this.value) { - return 5; + return 5 } - }, - }, - }); + } + } + }) const cleanedObject = await schema.clean({ $set: { - nested: [{}], - }, - }); + nested: [{}] + } + }) expect(cleanedObject).to.deep.equal({ $set: { nested: [ { doubleNested: { - integer: 5, - }, - }, - ], - }, - }); - }); + integer: 5 + } + } + ] + } + }) + }) it('updates deeply nested with $set having dotted array key', async function () { const schema = new SimpleSchema({ @@ -909,134 +909,134 @@ describe('autoValue', function () { 'nested.$.doubleNested': Object, 'nested.$.doubleNested.integer': { type: SimpleSchema.Integer, - autoValue() { + autoValue () { if (!this.value) { - return 5; + return 5 } - }, - }, - }); + } + } + }) const cleanedObject = await schema.clean({ $set: { - 'nested.0.doubleNested': {}, - }, - }); + 'nested.0.doubleNested': {} + } + }) expect(cleanedObject).to.deep.equal({ $set: { 'nested.0.doubleNested': { - integer: 5, - }, - }, - }); - }); + integer: 5 + } + } + }) + }) it('should add auto values to sub schemas for plain objects', async function () { const doubleNestedSchema = new SimpleSchema({ integer: { type: SimpleSchema.Integer, - autoValue() { + autoValue () { if (!this.value) { - return 5; + return 5 } - }, - }, - }); + } + } + }) const nestedSchema = new SimpleSchema({ - doubleNested: doubleNestedSchema, - }); + doubleNested: doubleNestedSchema + }) const schema = new SimpleSchema({ nested: Array, - 'nested.$': nestedSchema, - }); + 'nested.$': nestedSchema + }) const cleanedObject = await schema.clean({ nested: [ { - doubleNested: {}, + doubleNested: {} }, { doubleNested: { - integer: '8', - }, - }, - ], - }); + integer: '8' + } + } + ] + }) expect(cleanedObject).to.deep.equal({ nested: [ { doubleNested: { - integer: 5, - }, + integer: 5 + } }, { doubleNested: { - integer: 8, - }, - }, - ], - }); - }); + integer: 8 + } + } + ] + }) + }) it('should add auto values to sub schemas for modifiers objects', async function () { const doubleNestedSchema = new SimpleSchema({ integer: { type: SimpleSchema.Integer, - autoValue() { + autoValue () { if (!this.value) { - return 5; + return 5 } - }, - }, - }); + } + } + }) const nestedSchema = new SimpleSchema({ - doubleNested: doubleNestedSchema, - }); + doubleNested: doubleNestedSchema + }) const schema = new SimpleSchema({ nested: Array, - 'nested.$': nestedSchema, - }); + 'nested.$': nestedSchema + }) const cleanedObject = await schema.clean({ $push: { nested: { - doubleNested: {}, - }, - }, - }); + doubleNested: {} + } + } + }) expect(cleanedObject).to.deep.equal({ $push: { nested: { doubleNested: { - integer: 5, - }, - }, - }, - }); - }); + integer: 5 + } + } + } + }) + }) it('after cleaning with one extended, autoValues do not bleed over', async function () { const schema1 = new SimpleSchema({ n: Number, obj: { type: Object, - defaultValue: {}, - }, - }); + defaultValue: {} + } + }) const schema2 = schema1.clone().extend({ 'obj.b': { type: SimpleSchema.Integer, - defaultValue: 1, - }, - }); + defaultValue: 1 + } + }) // This is a bug where after you've run autoValues with schema2, which // is cloned from schema1, the schema2 autoValues are not set while @@ -1045,9 +1045,9 @@ describe('autoValue', function () { // {} because additional default values within that object would actually // be mutated onto the original object. We now clone autoValues in // AutoValueRunner to fix this. - expect(await schema1.clean({})).to.deep.equal({ obj: {} }); - expect(await schema2.clean({})).to.deep.equal({ obj: { b: 1 } }); - expect(await schema1.clean({})).to.deep.equal({ obj: {} }); - expect(await schema2.clean({})).to.deep.equal({ obj: { b: 1 } }); - }); -}); + expect(await schema1.clean({})).to.deep.equal({ obj: {} }) + expect(await schema2.clean({})).to.deep.equal({ obj: { b: 1 } }) + expect(await schema1.clean({})).to.deep.equal({ obj: {} }) + expect(await schema2.clean({})).to.deep.equal({ obj: { b: 1 } }) + }) +}) diff --git a/lib/clean/convertToProperType.js b/lib/clean/convertToProperType.js index 853eb8d..65ff886 100644 --- a/lib/clean/convertToProperType.js +++ b/lib/clean/convertToProperType.js @@ -1,4 +1,4 @@ -import { SimpleSchema } from '../SimpleSchema'; +import { SimpleSchema } from '../SimpleSchema' /** * Converts value to proper type @@ -7,29 +7,29 @@ import { SimpleSchema } from '../SimpleSchema'; * @param {Any} type A type * @returns {Any} Value converted to type. */ -function convertToProperType(value, type) { +function convertToProperType (value, type) { // Can't and shouldn't convert arrays or objects or null if ( - Array.isArray(value) - || (value && (typeof value === 'function' || typeof value === 'object') && !(value instanceof Date)) - || value === null - ) return value; + Array.isArray(value) || + (value && (typeof value === 'function' || typeof value === 'object') && !(value instanceof Date)) || + value === null + ) return value // Convert to String type if (type === String) { - if (value === null || value === undefined) return value; - return value.toString(); + if (value === null || value === undefined) return value + return value.toString() } // Convert to Number type if (type === Number || type === SimpleSchema.Integer) { if (typeof value === 'string' && value.length > 0) { // Try to convert numeric strings to numbers - const numberVal = Number(value); - if (!isNaN(numberVal)) return numberVal; + const numberVal = Number(value) + if (!isNaN(numberVal)) return numberVal } // Leave it; will fail validation - return value; + return value } // If target type is a Date we can safely convert from either a @@ -38,28 +38,28 @@ function convertToProperType(value, type) { // by Date. if (type === Date) { if (typeof value === 'string') { - const parsedDate = Date.parse(value); - if (isNaN(parsedDate) === false) return new Date(parsedDate); + const parsedDate = Date.parse(value) + if (isNaN(parsedDate) === false) return new Date(parsedDate) } - if (typeof value === 'number') return new Date(value); + if (typeof value === 'number') return new Date(value) } // Convert to Boolean type if (type === Boolean) { if (typeof value === 'string') { // Convert exact string 'true' and 'false' to true and false respectively - if (value.toLowerCase() === 'true') return true; - if (value.toLowerCase() === 'false') return false; + if (value.toLowerCase() === 'true') return true + if (value.toLowerCase() === 'false') return false } else if (typeof value === 'number' && !isNaN(value)) { // NaN can be error, so skipping it - return Boolean(value); + return Boolean(value) } } // If an array is what you want, I'll give you an array - if (type === Array) return [value]; + if (type === Array) return [value] // Could not convert - return value; + return value } -export default convertToProperType; +export default convertToProperType diff --git a/lib/clean/convertToProperType.tests.js b/lib/clean/convertToProperType.tests.js index dd6e86f..c36c6e7 100644 --- a/lib/clean/convertToProperType.tests.js +++ b/lib/clean/convertToProperType.tests.js @@ -1,38 +1,38 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import convertToProperType from './convertToProperType'; +import { expect } from 'chai' +import convertToProperType from './convertToProperType' describe('convertToProperType', function () { it('convert string `false` to boolean value false', function () { - expect(convertToProperType('false', Boolean)).to.equal(false); - }); + expect(convertToProperType('false', Boolean)).to.equal(false) + }) it('convert string `FALSE` to boolean value false', function () { - expect(convertToProperType('FALSE', Boolean)).to.equal(false); - }); + expect(convertToProperType('FALSE', Boolean)).to.equal(false) + }) it('convert string `true` to boolean value true', function () { - expect(convertToProperType('true', Boolean)).to.equal(true); - }); + expect(convertToProperType('true', Boolean)).to.equal(true) + }) it('convert string `TRUE` to boolean value true', function () { - expect(convertToProperType('TRUE', Boolean)).to.equal(true); - }); + expect(convertToProperType('TRUE', Boolean)).to.equal(true) + }) it('convert number 1 to boolean value true', function () { - expect(convertToProperType(1, Boolean)).to.equal(true); - }); + expect(convertToProperType(1, Boolean)).to.equal(true) + }) it('convert number 0 to boolean value false', function () { - expect(convertToProperType(0, Boolean)).to.equal(false); - }); + expect(convertToProperType(0, Boolean)).to.equal(false) + }) it('don\'t convert NaN to boolean value', function () { - expect(convertToProperType(Number('text'), Boolean)).to.deep.equal(NaN); - }); + expect(convertToProperType(Number('text'), Boolean)).to.deep.equal(NaN) + }) it('does not try to convert null', function () { - expect(convertToProperType(null, Array)).to.equal(null); - }); -}); + expect(convertToProperType(null, Array)).to.equal(null) + }) +}) diff --git a/lib/clean/defaultValue.tests.js b/lib/clean/defaultValue.tests.js index adca8e5..56f1d28 100644 --- a/lib/clean/defaultValue.tests.js +++ b/lib/clean/defaultValue.tests.js @@ -1,7 +1,7 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import { SimpleSchema } from '../SimpleSchema'; +import { expect } from 'chai' +import { SimpleSchema } from '../SimpleSchema' describe('defaultValue', function () { describe('normal objects', function () { @@ -10,488 +10,488 @@ describe('defaultValue', function () { name: { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({}); + const result = await schema.clean({}) - expect(result).to.deep.equal({ name: 'Test' }); - }); + expect(result).to.deep.equal({ name: 'Test' }) + }) it('does not add default value for already set top-level simple prop', async function () { const schema = new SimpleSchema({ name: { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({ name: 'Other' }); + const result = await schema.clean({ name: 'Other' }) - expect(result).to.deep.equal({ name: 'Other' }); - }); + expect(result).to.deep.equal({ name: 'Other' }) + }) it('adds default value for missing top-level array prop', async function () { const schema = new SimpleSchema({ names: { type: Array, defaultValue: [], - optional: true, + optional: true }, - 'names.$': String, - }); + 'names.$': String + }) - const result = await schema.clean({}); + const result = await schema.clean({}) - expect(result).to.deep.equal({ names: [] }); - }); + expect(result).to.deep.equal({ names: [] }) + }) it('does not add default value for top-level array prop that is already set', async function () { const schema = new SimpleSchema({ names: { type: Array, defaultValue: [], - optional: true, + optional: true }, - 'names.$': String, - }); + 'names.$': String + }) - const result = await schema.clean({ names: ['foo', 'bar'] }); + const result = await schema.clean({ names: ['foo', 'bar'] }) - expect(result).to.deep.equal({ names: ['foo', 'bar'] }); - }); + expect(result).to.deep.equal({ names: ['foo', 'bar'] }) + }) it('does not add defaultValue for prop in object, if object is not set', async function () { const schema = new SimpleSchema({ a: { type: Object, - optional: true, + optional: true }, 'a.b': { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({}); + const result = await schema.clean({}) - expect(result).to.deep.equal({}); - }); + expect(result).to.deep.equal({}) + }) it('adds defaultValue for prop in object, if object is set in object being cleaned', async function () { const schema = new SimpleSchema({ a: { type: Object, - optional: true, + optional: true }, 'a.b': { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({ a: {} }); + const result = await schema.clean({ a: {} }) - expect(result).to.deep.equal({ a: { b: 'Test' } }); - }); + expect(result).to.deep.equal({ a: { b: 'Test' } }) + }) it('adds defaultValue for prop in objects within array, if object is set in object being cleaned', async function () { const schema = new SimpleSchema({ b: { type: Array, - optional: true, + optional: true }, 'b.$': { - type: Object, + type: Object }, 'b.$.a': { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({ b: [{}, {}] }); + const result = await schema.clean({ b: [{}, {}] }) - expect(result).to.deep.equal({ b: [{ a: 'Test' }, { a: 'Test' }] }); - }); + expect(result).to.deep.equal({ b: [{ a: 'Test' }, { a: 'Test' }] }) + }) it('does not add defaultValue for prop in objects within array, if the prop is already set in object being cleaned', async function () { const schema = new SimpleSchema({ b: { type: Array, - optional: true, + optional: true }, 'b.$': { - type: Object, + type: Object }, 'b.$.a': { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({ b: [{ a: 'Other' }] }); + const result = await schema.clean({ b: [{ a: 'Other' }] }) - expect(result).to.deep.equal({ b: [{ a: 'Other' }] }); - }); + expect(result).to.deep.equal({ b: [{ a: 'Other' }] }) + }) it('adds defaultValue for prop in objects within array, if array and object are set by array defaultValue', async function () { const schema = new SimpleSchema({ b: { type: Array, optional: true, - defaultValue: [{}, { a: 'Other' }], + defaultValue: [{}, { a: 'Other' }] }, 'b.$': { - type: Object, + type: Object }, 'b.$.a': { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({}); + const result = await schema.clean({}) - expect(result).to.deep.equal({ b: [{ a: 'Test' }, { a: 'Other' }] }); - }); + expect(result).to.deep.equal({ b: [{ a: 'Test' }, { a: 'Other' }] }) + }) it('adds defaultValue for prop in object, if object is set by another defaultValue', async function () { const schema = new SimpleSchema({ a: { type: Object, defaultValue: {}, - optional: true, + optional: true }, 'a.b': { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({}); + const result = await schema.clean({}) - expect(result).to.deep.equal({ a: { b: 'Test' } }); - }); + expect(result).to.deep.equal({ a: { b: 'Test' } }) + }) it('does not add defaultValue for prop in object, if prop already has value in object being cleaned', async function () { const schema = new SimpleSchema({ a: { type: Object, - optional: true, + optional: true }, 'a.b': { type: String, defaultValue: 'Test', - optional: true, - }, - }); + optional: true + } + }) - const result = await schema.clean({ a: { b: 'Other' } }); + const result = await schema.clean({ a: { b: 'Other' } }) - expect(result).to.deep.equal({ a: { b: 'Other' } }); - }); + expect(result).to.deep.equal({ a: { b: 'Other' } }) + }) it('adds boolean true default value', async function () { const schema = new SimpleSchema({ bool: { type: Boolean, - defaultValue: true, - }, - }); + defaultValue: true + } + }) - const result = await schema.clean({}); - expect(result).to.deep.equal({ bool: true }); - }); + const result = await schema.clean({}) + expect(result).to.deep.equal({ bool: true }) + }) it('adds boolean false default value', async function () { const schema = new SimpleSchema({ bool: { type: Boolean, - defaultValue: false, - }, - }); + defaultValue: false + } + }) - const result = await schema.clean({}); - expect(result).to.deep.equal({ bool: false }); - }); - }); + const result = await schema.clean({}) + expect(result).to.deep.equal({ bool: false }) + }) + }) describe('modifier object', function () { it('adds to $set object', async function () { const schema = new SimpleSchema({ obj: { - type: Object, + type: Object }, 'obj.a': { type: Number, - optional: true, + optional: true }, 'obj.b': { type: Number, optional: true, - defaultValue: 10, - }, - }); + defaultValue: 10 + } + }) const result = await schema.clean({ $set: { - obj: { a: 1 }, - }, - }); + obj: { a: 1 } + } + }) expect(result).to.deep.equal({ $set: { - obj: { a: 1, b: 10 }, - }, - }); - }); + obj: { a: 1, b: 10 } + } + }) + }) it('adds to $set object with dotted set prop', async function () { const schema = new SimpleSchema({ obj: { - type: Object, + type: Object }, 'obj.a': { type: Object, - optional: true, + optional: true }, 'obj.a.foo': { type: Number, optional: true, - defaultValue: 20, + defaultValue: 20 }, 'obj.b': { type: Number, optional: true, - defaultValue: 10, - }, - }); + defaultValue: 10 + } + }) const result = await schema.clean( { $set: { - 'obj.a': {}, - }, + 'obj.a': {} + } }, { isModifier: true, - isUpsert: true, - }, - ); + isUpsert: true + } + ) expect(result).to.deep.equal({ $set: { - 'obj.a': { foo: 20 }, + 'obj.a': { foo: 20 } }, $setOnInsert: { - 'obj.b': 10, - }, - }); - }); + 'obj.b': 10 + } + }) + }) it('adds to $set object with dotted set prop and array', async function () { const schema = new SimpleSchema({ obj: { - type: Object, + type: Object }, 'obj.a': { type: Object, - optional: true, + optional: true }, 'obj.a.foo': { type: Array, - optional: true, + optional: true }, 'obj.a.foo.$': Object, 'obj.a.foo.$.bar': { type: Number, optional: true, - defaultValue: 200, - }, - }); + defaultValue: 200 + } + }) let result = await schema.clean({ $set: { - 'obj.a': {}, - }, - }); + 'obj.a': {} + } + }) expect(result).to.deep.equal({ $set: { - 'obj.a': {}, - }, - }); + 'obj.a': {} + } + }) result = await schema.clean({ $set: { - 'obj.a': { foo: [] }, - }, - }); + 'obj.a': { foo: [] } + } + }) expect(result).to.deep.equal({ $set: { - 'obj.a': { foo: [] }, - }, - }); + 'obj.a': { foo: [] } + } + }) result = await schema.clean({ $set: { - 'obj.a': { foo: [{}, {}] }, - }, - }); + 'obj.a': { foo: [{}, {}] } + } + }) expect(result).to.deep.equal({ $set: { - 'obj.a': { foo: [{ bar: 200 }, { bar: 200 }] }, - }, - }); - }); + 'obj.a': { foo: [{ bar: 200 }, { bar: 200 }] } + } + }) + }) it('adds a $setOnInsert if $setting a sibling prop', async function () { const schema = new SimpleSchema({ obj: { - type: Object, + type: Object }, 'obj.a': { type: Number, - optional: true, + optional: true }, 'obj.b': { type: Number, optional: true, - defaultValue: 10, + defaultValue: 10 }, 'obj.c': { type: Number, optional: true, - defaultValue: 50, - }, - }); + defaultValue: 50 + } + }) const result = await schema.clean( { $set: { 'obj.a': 100, - 'obj.c': 2, - }, + 'obj.c': 2 + } }, { isModifier: true, - isUpsert: true, - }, - ); + isUpsert: true + } + ) expect(result).to.deep.equal({ $set: { 'obj.a': 100, - 'obj.c': 2, + 'obj.c': 2 }, $setOnInsert: { - 'obj.b': 10, - }, - }); - }); + 'obj.b': 10 + } + }) + }) it('adds a $setOnInsert if $setting a sibling child prop', async function () { const schema = new SimpleSchema({ obj: { - type: Object, + type: Object }, 'obj.a': { type: Object, - optional: true, + optional: true }, 'obj.a.one': { type: Number, optional: true, - defaultValue: 500, + defaultValue: 500 }, 'obj.a.two': { type: Number, optional: true, - defaultValue: 1000, + defaultValue: 1000 }, 'obj.b': { type: Number, optional: true, - defaultValue: 10, + defaultValue: 10 }, 'obj.c': { type: Number, optional: true, - defaultValue: 50, - }, - }); + defaultValue: 50 + } + }) const result = await schema.clean( { $set: { - 'obj.a.one': 100, - }, + 'obj.a.one': 100 + } }, { isModifier: true, - isUpsert: true, - }, - ); + isUpsert: true + } + ) expect(result).to.deep.equal({ $set: { - 'obj.a.one': 100, + 'obj.a.one': 100 }, $setOnInsert: { 'obj.a.two': 1000, 'obj.b': 10, - 'obj.c': 50, - }, - }); - }); + 'obj.c': 50 + } + }) + }) it('adds $setOnInsert for top-level prop', async function () { const schema = new SimpleSchema({ foo: { type: String, - defaultValue: 'Test', + defaultValue: 'Test' }, names: { type: Array, - optional: true, + optional: true }, 'names.$': { - type: String, - }, - }); + type: String + } + }) const result = await schema.clean( { $addToSet: { - names: 'new value', - }, + names: 'new value' + } }, { isModifier: true, - isUpsert: true, - }, - ); + isUpsert: true + } + ) expect(result).to.deep.equal({ $addToSet: { - names: 'new value', + names: 'new value' }, $setOnInsert: { - foo: 'Test', - }, - }); - }); + foo: 'Test' + } + }) + }) it('adds default values to object being $pushed into array', async function () { const schema = new SimpleSchema({ @@ -499,216 +499,216 @@ describe('defaultValue', function () { 'things.$': Object, 'things.$.a': { type: String, - defaultValue: 'foo', + defaultValue: 'foo' }, 'things.$.b': { type: String, - defaultValue: 'bar', - }, - }); + defaultValue: 'bar' + } + }) const result = await schema.clean({ $push: { - things: {}, - }, - }); + things: {} + } + }) expect(result).to.deep.equal({ $push: { things: { a: 'foo', - b: 'bar', - }, - }, - }); - }); - }); + b: 'bar' + } + } + }) + }) + }) it('nested defaultValue for prop in obj in array', async function () { const listItemSchema = new SimpleSchema({ foo: { type: String, defaultValue: 'TEST', - optional: true, - }, - }); + optional: true + } + }) const detailsSchema = new SimpleSchema({ list: { type: Array, - optional: true, + optional: true }, - 'list.$': listItemSchema, - }); + 'list.$': listItemSchema + }) const schema = new SimpleSchema({ name: String, details: { type: detailsSchema, - optional: true, - }, - }); + optional: true + } + }) const cleanedObject = await schema.clean({ name: 'NAME', - details: {}, - }); + details: {} + }) expect(cleanedObject).to.deep.equal({ name: 'NAME', - details: {}, - }); - }); + details: {} + }) + }) it('issue 426', async function () { const schema = new SimpleSchema({ name: { - type: String, + type: String }, images: { type: Array, label: 'Images', minCount: 0, - defaultValue: [], + defaultValue: [] }, 'images.$': { type: Object, - label: 'Image', - }, - }); + label: 'Image' + } + }) const doc = { - name: 'Test', - }; + name: 'Test' + } expect(await schema.clean(doc)).to.deep.equal({ name: 'Test', - images: [], - }); - }); + images: [] + }) + }) it('complex with .$. modifier', async () => { const fooSchema = new SimpleSchema({ bar: { type: String, optional: true, - defaultValue: 'TEST', - }, - }); + defaultValue: 'TEST' + } + }) const itemSchema = new SimpleSchema({ foo: { type: fooSchema, - optional: true, - }, - }); + optional: true + } + }) const schema = new SimpleSchema({ items: { type: Array, - optional: true, + optional: true }, 'items.$': { - type: itemSchema, - }, - }); + type: itemSchema + } + }) let result = await schema.clean({ $set: { - 'items.$.foo': { bar: 'OTHER' }, - }, - }); + 'items.$.foo': { bar: 'OTHER' } + } + }) expect(result).to.deep.equal({ $set: { - 'items.$.foo': { bar: 'OTHER' }, - }, - }); + 'items.$.foo': { bar: 'OTHER' } + } + }) result = await schema.clean({ $addToSet: { items: { - foo: { bar: 'OTHER' }, - }, - }, - }); + foo: { bar: 'OTHER' } + } + } + }) expect(result).to.deep.equal({ $addToSet: { items: { - foo: { bar: 'OTHER' }, - }, - }, - }); - }); + foo: { bar: 'OTHER' } + } + } + }) + }) it('$setOnInsert are correctly added with path notation', async function () { const schema = new SimpleSchema({ settings: { type: Object, optional: true, - defaultValue: {}, + defaultValue: {} }, 'settings.bool': { type: Boolean, - defaultValue: false, + defaultValue: false }, 'settings.obj': { type: Object, optional: true, - defaultValue: {}, + defaultValue: {} }, 'settings.obj.bool': { type: Boolean, optional: true, - defaultValue: false, + defaultValue: false }, 'settings.obj.name': { type: Boolean, optional: true, - defaultValue: 'foo', + defaultValue: 'foo' }, 'settings.obj2': { type: Object, optional: true, - defaultValue: {}, + defaultValue: {} }, 'settings.obj2.bool': { type: Boolean, optional: true, - defaultValue: false, + defaultValue: false }, - 'settings.obj2.name': String, - }); + 'settings.obj2.name': String + }) expect( await schema.clean( { $set: { - 'settings.obj.bool': true, + 'settings.obj.bool': true }, $unset: { - 'settings.obj2.name': '', - }, + 'settings.obj2.name': '' + } }, { isModifier: true, - isUpsert: true, - }, - ), + isUpsert: true + } + ) ).to.deep.equal({ $set: { - 'settings.obj.bool': true, + 'settings.obj.bool': true }, $unset: { - 'settings.obj2.name': '', + 'settings.obj2.name': '' }, $setOnInsert: { 'settings.bool': false, 'settings.obj.name': 'foo', - 'settings.obj2': { bool: false }, - }, - }); - }); + 'settings.obj2': { bool: false } + } + }) + }) it('$setOnInsert are correctly added with path notation - v2', async function () { // This is the same as the test above, except that there is no default @@ -718,160 +718,160 @@ describe('defaultValue', function () { settings: { type: Object, optional: true, - defaultValue: {}, + defaultValue: {} }, 'settings.bool': { type: Boolean, - defaultValue: false, + defaultValue: false }, 'settings.obj': { type: Object, optional: true, - defaultValue: {}, + defaultValue: {} }, 'settings.obj.bool': { type: Boolean, optional: true, - defaultValue: false, + defaultValue: false }, 'settings.obj.name': { type: Boolean, optional: true, - defaultValue: 'foo', + defaultValue: 'foo' }, 'settings.obj2': { type: Object, - optional: true, + optional: true }, 'settings.obj2.bool': { type: Boolean, optional: true, - defaultValue: false, + defaultValue: false }, - 'settings.obj2.name': String, - }); + 'settings.obj2.name': String + }) expect( await schema.clean( { $set: { - 'settings.obj.bool': true, + 'settings.obj.bool': true }, $unset: { - 'settings.obj2.name': '', - }, + 'settings.obj2.name': '' + } }, { isModifier: true, - isUpsert: true, - }, - ), + isUpsert: true + } + ) ).to.deep.equal({ $set: { - 'settings.obj.bool': true, + 'settings.obj.bool': true }, $unset: { - 'settings.obj2.name': '', + 'settings.obj2.name': '' }, $setOnInsert: { 'settings.bool': false, - 'settings.obj.name': 'foo', - }, - }); - }); + 'settings.obj.name': 'foo' + } + }) + }) it('default value for sibling field added by $addToSet', async function () { const AddressItem = new SimpleSchema({ fullName: String, address1: String, - address2: String, - }); + address2: String + }) const Profile = new SimpleSchema({ addressBook: { type: Array, - optional: true, + optional: true }, 'addressBook.$': { - type: AddressItem, + type: AddressItem }, invited: { type: Boolean, - defaultValue: false, - }, - }); + defaultValue: false + } + }) const schema = new SimpleSchema({ profile: { type: Profile, - optional: true, - }, - }); + optional: true + } + }) const accountsUpdateQuery = { $addToSet: { 'profile.addressBook': { fullName: 'Sonny Hayes', address1: '518 Nader Rapids', - address2: 'Apt. 893', - }, - }, - }; + address2: 'Apt. 893' + } + } + } - const cleanedModifier = await schema.clean(accountsUpdateQuery, { isModifier: true, isUpsert: true }); + const cleanedModifier = await schema.clean(accountsUpdateQuery, { isModifier: true, isUpsert: true }) expect(cleanedModifier).to.deep.equal({ $addToSet: { 'profile.addressBook': { fullName: 'Sonny Hayes', address1: '518 Nader Rapids', - address2: 'Apt. 893', - }, + address2: 'Apt. 893' + } }, $setOnInsert: { - 'profile.invited': false, - }, - }); - }); + 'profile.invited': false + } + }) + }) it('does not add $setOnInsert to modifiers normally', async function () { const schema = new SimpleSchema({ name: String, - isOwner: { type: Boolean, defaultValue: true }, - }); + isOwner: { type: Boolean, defaultValue: true } + }) expect( await schema.clean( { - $set: { name: 'Phil' }, + $set: { name: 'Phil' } }, { - isModifier: true, - }, - ), + isModifier: true + } + ) ).to.deep.equal({ - $set: { name: 'Phil' }, - }); - }); + $set: { name: 'Phil' } + }) + }) it('adds $setOnInsert to modifiers when isUpsert it true', async function () { const schema = new SimpleSchema({ name: String, - isOwner: { type: Boolean, defaultValue: true }, - }); + isOwner: { type: Boolean, defaultValue: true } + }) expect( await schema.clean( { - $set: { name: 'Phil' }, + $set: { name: 'Phil' } }, { isModifier: true, - isUpsert: true, - }, - ), + isUpsert: true + } + ) ).to.deep.equal({ $set: { name: 'Phil' }, - $setOnInsert: { isOwner: true }, - }); - }); -}); + $setOnInsert: { isOwner: true } + }) + }) +}) diff --git a/lib/clean/getPositionsForAutoValue.js b/lib/clean/getPositionsForAutoValue.js index 8c2a2bb..634ef77 100644 --- a/lib/clean/getPositionsForAutoValue.js +++ b/lib/clean/getPositionsForAutoValue.js @@ -1,5 +1,5 @@ -import MongoObject from 'mongo-object'; -import { getLastPartOfKey, getParentOfKey } from '../utility'; +import MongoObject from 'mongo-object' +import { getLastPartOfKey, getParentOfKey } from '../utility' /** * A position is a place in the object where this field exists. @@ -26,14 +26,14 @@ import { getLastPartOfKey, getParentOfKey } from '../utility'; * but also the positions that might exist due to their parent object existing or their * parent object being auto-created by a MongoDB modifier that implies it. */ -export default function getPositionsForAutoValue({ fieldName, isModifier, mongoObject }) { +export default function getPositionsForAutoValue ({ fieldName, isModifier, mongoObject }) { // Positions for this field - const positions = mongoObject.getPositionsInfoForGenericKey(fieldName); + const positions = mongoObject.getPositionsInfoForGenericKey(fieldName) // If the field is an object and will be created by MongoDB, // we don't need (and can't have) a value for it if (isModifier && mongoObject.getPositionsThatCreateGenericKey(fieldName).length > 0) { - return positions; + return positions } // For simple top-level fields, just add an undefined would-be position @@ -43,60 +43,60 @@ export default function getPositionsForAutoValue({ fieldName, isModifier, mongoO key: fieldName, value: undefined, operator: isModifier ? '$set' : null, - position: isModifier ? `$set[${fieldName}]` : fieldName, - }); - return positions; + position: isModifier ? `$set[${fieldName}]` : fieldName + }) + return positions } - const parentPath = getParentOfKey(fieldName); - const lastPart = getLastPartOfKey(fieldName, parentPath); - const lastPartWithBraces = lastPart.replace(/\./g, ']['); - const parentPositions = mongoObject.getPositionsInfoForGenericKey(parentPath); + const parentPath = getParentOfKey(fieldName) + const lastPart = getLastPartOfKey(fieldName, parentPath) + const lastPartWithBraces = lastPart.replace(/\./g, '][') + const parentPositions = mongoObject.getPositionsInfoForGenericKey(parentPath) if (parentPositions.length) { parentPositions.forEach((info) => { - const childPosition = `${info.position}[${lastPartWithBraces}]`; + const childPosition = `${info.position}[${lastPartWithBraces}]` if (!positions.find((i) => i.position === childPosition)) { positions.push({ key: `${info.key}.${lastPart}`, value: undefined, operator: info.operator, - position: childPosition, - }); + position: childPosition + }) } - }); + }) } else if (parentPath.slice(-2) !== '.$') { // positions that will create parentPath mongoObject.getPositionsThatCreateGenericKey(parentPath).forEach((info) => { - const { operator, position } = info; - let wouldBePosition; + const { operator, position } = info + let wouldBePosition if (operator) { - const next = position.slice(position.indexOf('[') + 1, position.indexOf(']')); - const nextPieces = next.split('.'); + const next = position.slice(position.indexOf('[') + 1, position.indexOf(']')) + const nextPieces = next.split('.') - const newPieces = []; - let newKey; + const newPieces = [] + let newKey while (nextPieces.length && newKey !== parentPath) { - newPieces.push(nextPieces.shift()); - newKey = newPieces.join('.'); + newPieces.push(nextPieces.shift()) + newKey = newPieces.join('.') } - newKey = `${newKey}.${fieldName.slice(newKey.length + 1)}`; - wouldBePosition = `$set[${newKey}]`; + newKey = `${newKey}.${fieldName.slice(newKey.length + 1)}` + wouldBePosition = `$set[${newKey}]` } else { - const lastPart2 = getLastPartOfKey(fieldName, parentPath); - const lastPartWithBraces2 = lastPart2.replace(/\./g, ']['); - wouldBePosition = `${position.slice(0, position.lastIndexOf('['))}[${lastPartWithBraces2}]`; + const lastPart2 = getLastPartOfKey(fieldName, parentPath) + const lastPartWithBraces2 = lastPart2.replace(/\./g, '][') + wouldBePosition = `${position.slice(0, position.lastIndexOf('['))}[${lastPartWithBraces2}]` } if (!positions.find((i) => i.position === wouldBePosition)) { positions.push({ key: MongoObject._positionToKey(wouldBePosition), value: undefined, operator: operator ? '$set' : null, - position: wouldBePosition, - }); + position: wouldBePosition + }) } - }); + }) } - return positions; + return positions } diff --git a/lib/clean/setAutoValues.js b/lib/clean/setAutoValues.js index 8129422..ff6ba72 100755 --- a/lib/clean/setAutoValues.js +++ b/lib/clean/setAutoValues.js @@ -1,5 +1,5 @@ -import getPositionsForAutoValue from './getPositionsForAutoValue'; -import AutoValueRunner from './AutoValueRunner'; +import getPositionsForAutoValue from './getPositionsForAutoValue' +import AutoValueRunner from './AutoValueRunner' /** * @method sortAutoValueFunctions @@ -9,19 +9,19 @@ import AutoValueRunner from './AutoValueRunner'; * * Stable sort of the autoValueFunctions (preserves order at the same field depth). */ -export function sortAutoValueFunctions(autoValueFunctions) { +export function sortAutoValueFunctions (autoValueFunctions) { const defaultFieldOrder = autoValueFunctions.reduce((acc, { fieldName }, index) => { - acc[fieldName] = index; - return acc; - }, {}); + acc[fieldName] = index + return acc + }, {}) // Sort by how many dots each field name has, asc, such that we can auto-create // objects and arrays before we run the autoValues for properties within them. // Fields of the same level (same number of dots) preserve should order from the original array. return autoValueFunctions.sort((a, b) => { - const depthDiff = a.fieldName.split('.').length - b.fieldName.split('.').length; - return depthDiff === 0 ? defaultFieldOrder[a.fieldName] - defaultFieldOrder[b.fieldName] : depthDiff; - }); + const depthDiff = a.fieldName.split('.').length - b.fieldName.split('.').length + return depthDiff === 0 ? defaultFieldOrder[a.fieldName] - defaultFieldOrder[b.fieldName] : depthDiff + }) } /** @@ -36,28 +36,28 @@ export function sortAutoValueFunctions(autoValueFunctions) { * Updates doc with automatic values from autoValue functions or default * values from defaultValue. Modifies the referenced object in place. */ -async function setAutoValues(autoValueFunctions, mongoObject, isModifier, isUpsert, extendedAutoValueContext) { - const sortedAutoValueFunctions = sortAutoValueFunctions(autoValueFunctions); +async function setAutoValues (autoValueFunctions, mongoObject, isModifier, isUpsert, extendedAutoValueContext) { + const sortedAutoValueFunctions = sortAutoValueFunctions(autoValueFunctions) for (const sortedItem of sortedAutoValueFunctions) { - const { func, fieldName, closestSubschemaFieldName } = sortedItem; + const { func, fieldName, closestSubschemaFieldName } = sortedItem const avRunner = new AutoValueRunner({ closestSubschemaFieldName, extendedAutoValueContext, func, isModifier, isUpsert, - mongoObject, - }); + mongoObject + }) - const positions = getPositionsForAutoValue({ fieldName, isModifier, mongoObject }); + const positions = getPositionsForAutoValue({ fieldName, isModifier, mongoObject }) // Run the autoValue function once for each place in the object that // has a value or that potentially should. for (const position of positions) { - await avRunner.runForPosition(position); + await avRunner.runForPosition(position) } } } -export default setAutoValues; +export default setAutoValues diff --git a/lib/clean/setAutoValues.tests.js b/lib/clean/setAutoValues.tests.js index a811376..1d6b184 100755 --- a/lib/clean/setAutoValues.tests.js +++ b/lib/clean/setAutoValues.tests.js @@ -1,69 +1,69 @@ -import { expect } from 'chai'; -import { SimpleSchema } from '../SimpleSchema'; -import { sortAutoValueFunctions } from './setAutoValues'; +import { expect } from 'chai' +import { SimpleSchema } from '../SimpleSchema' +import { sortAutoValueFunctions } from './setAutoValues' describe('setAutoValues', () => { it('sorts correctly', () => { const schema = new SimpleSchema({ field1: { type: String, - autoValue() {}, + autoValue () {} }, field2: { type: String, - autoValue() {}, + autoValue () {} }, field3: { type: Number, - autoValue() {}, + autoValue () {} }, nested: Object, 'nested.field1': { type: String, - autoValue() {}, + autoValue () {} }, 'nested.field2': { type: String, - autoValue() {}, + autoValue () {} }, 'nested.field3': { type: String, - autoValue() {}, + autoValue () {} }, 'nested.field4': { type: String, - defaultValue: 'test', + defaultValue: 'test' }, field4: { type: Number, - autoValue() {}, + autoValue () {} }, field5: { type: Number, - autoValue() {}, + autoValue () {} }, field6: { type: String, - autoValue() {}, + autoValue () {} }, field7: { type: String, - autoValue() {}, - }, - }); + autoValue () {} + } + }) - const autoValueFunctions = schema.autoValueFunctions(); - const sorted = sortAutoValueFunctions(autoValueFunctions); + const autoValueFunctions = schema.autoValueFunctions() + const sorted = sortAutoValueFunctions(autoValueFunctions) - const FIELD_COUNT = 7; - const NESTED_FIELD_COUNT = 4; + const FIELD_COUNT = 7 + const NESTED_FIELD_COUNT = 4 // expecting: field1, field2, ..., field7, nested.field1, ... nested.field4 - const fieldOrder = sorted.map(({ fieldName }) => fieldName); + const fieldOrder = sorted.map(({ fieldName }) => fieldName) for (let i = 0; i < FIELD_COUNT; ++i) { - expect(fieldOrder[i]).to.equal(`field${i + 1}`); + expect(fieldOrder[i]).to.equal(`field${i + 1}`) } for (let i = FIELD_COUNT; i < FIELD_COUNT + NESTED_FIELD_COUNT; ++i) { - expect(fieldOrder[i]).to.equal(`nested.field${i - FIELD_COUNT + 1}`); + expect(fieldOrder[i]).to.equal(`nested.field${i - FIELD_COUNT + 1}`) } - }); -}); + }) +}) diff --git a/lib/defaultMessages.js b/lib/defaultMessages.js index f359f6c..9e86b18 100644 --- a/lib/defaultMessages.js +++ b/lib/defaultMessages.js @@ -1,4 +1,4 @@ -import regExpObj from './regExp'; +import regExpObj from './regExp' const regExpMessages = [ { exp: regExpObj.Email, msg: 'must be a valid email address' }, @@ -11,8 +11,8 @@ const regExpMessages = [ { exp: regExpObj.Url, msg: 'must be a valid URL' }, { exp: regExpObj.Id, msg: 'must be a valid alphanumeric ID' }, { exp: regExpObj.ZipCode, msg: 'must be a valid ZIP code' }, - { exp: regExpObj.Phone, msg: 'must be a valid phone number' }, -]; + { exp: regExpObj.Phone, msg: 'must be a valid phone number' } +] const defaultMessages = { initialLanguage: 'en', @@ -33,23 +33,23 @@ const defaultMessages = { noDecimal: '{{{label}}} must be an integer', notAllowed: '{{{value}}} is not an allowed value', expectedType: '{{{label}}} must be of type {{dataType}}', - regEx({ + regEx ({ label, - regExp, + regExp }) { // See if there's one where exp matches this expression - let msgObj; + let msgObj if (regExp) { - msgObj = regExpMessages.find((o) => o.exp && o.exp.toString() === regExp); + msgObj = regExpMessages.find((o) => o.exp && o.exp.toString() === regExp) } - const regExpMessage = msgObj ? msgObj.msg : 'failed regular expression validation'; + const regExpMessage = msgObj ? msgObj.msg : 'failed regular expression validation' - return `${label} ${regExpMessage}`; + return `${label} ${regExpMessage}` }, - keyNotInSchema: '{{name}} is not allowed by the schema', - }, - }, -}; + keyNotInSchema: '{{name}} is not allowed by the schema' + } + } +} -export default defaultMessages; +export default defaultMessages diff --git a/lib/doValidation.js b/lib/doValidation.js index f4f44bd..9466951 100644 --- a/lib/doValidation.js +++ b/lib/doValidation.js @@ -1,18 +1,18 @@ -import MongoObject from 'mongo-object'; -import { SimpleSchema } from './SimpleSchema'; +import MongoObject from 'mongo-object' +import { SimpleSchema } from './SimpleSchema' import { appendAffectedKey, getParentOfKey, looksLikeModifier, - isObjectWeShouldTraverse, -} from './utility'; -import typeValidator from './validation/typeValidator'; -import requiredValidator from './validation/requiredValidator'; -import allowedValuesValidator from './validation/allowedValuesValidator'; - -function shouldCheck(key) { - if (key === '$pushAll') throw new Error('$pushAll is not supported; use $push + $each'); - return ['$pull', '$pullAll', '$pop', '$slice'].indexOf(key) === -1; + isObjectWeShouldTraverse +} from './utility' +import typeValidator from './validation/typeValidator' +import requiredValidator from './validation/requiredValidator' +import allowedValuesValidator from './validation/allowedValuesValidator' + +function shouldCheck (key) { + if (key === '$pushAll') throw new Error('$pushAll is not supported; use $push + $each') + return ['$pull', '$pullAll', '$pop', '$slice'].indexOf(key) === -1 } /** @@ -29,7 +29,7 @@ function shouldCheck(key) { * @param validationContext * @return {*[]} */ -function doValidation({ +function doValidation ({ extendedCustomContext, ignoreTypes, isModifier, @@ -38,44 +38,44 @@ function doValidation({ mongoObject, obj, schema, - validationContext, + validationContext }) { // First do some basic checks of the object, and throw errors if necessary if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new Error('The first argument of validate() must be an object'); + throw new Error('The first argument of validate() must be an object') } if (!isModifier && looksLikeModifier(obj)) { - throw new Error('When the validation object contains mongo operators, you must set the modifier option to true'); + throw new Error('When the validation object contains mongo operators, you must set the modifier option to true') } - function getFieldInfo(key) { + function getFieldInfo (key) { // Create mongoObject if necessary, cache for speed - if (!mongoObject) mongoObject = new MongoObject(obj, schema.blackboxKeys()); + if (!mongoObject) mongoObject = new MongoObject(obj, schema.blackboxKeys()) - const keyInfo = mongoObject.getInfoForKey(key) || {}; + const keyInfo = mongoObject.getInfoForKey(key) || {} return { isSet: (keyInfo.value !== undefined), value: keyInfo.value, - operator: keyInfo.operator || null, - }; + operator: keyInfo.operator || null + } } - let validationErrors = []; + let validationErrors = [] // Validation function called for each affected key - function validate(val, affectedKey, affectedKeyGeneric, def, op, isInArrayItemObject, isInSubObject) { + function validate (val, affectedKey, affectedKeyGeneric, def, op, isInArrayItemObject, isInSubObject) { // Get the schema for this key, marking invalid if there isn't one. if (!def) { // We don't need KEY_NOT_IN_SCHEMA error for $unset and we also don't need to continue - if (op === '$unset' || (op === '$currentDate' && affectedKey.endsWith('.$type'))) return; + if (op === '$unset' || (op === '$currentDate' && affectedKey.endsWith('.$type'))) return validationErrors.push({ name: affectedKey, type: SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA, - value: val, - }); - return; + value: val + }) + return } // For $rename, make sure that the new name is allowed by the schema @@ -83,23 +83,23 @@ function doValidation({ validationErrors.push({ name: val, type: SimpleSchema.ErrorTypes.KEY_NOT_IN_SCHEMA, - value: null, - }); - return; + value: null + }) + return } // Prepare the context object for the validator functions - const fieldParentNameWithEndDot = getParentOfKey(affectedKey, true); - const fieldParentName = fieldParentNameWithEndDot.slice(0, -1); + const fieldParentNameWithEndDot = getParentOfKey(affectedKey, true) + const fieldParentName = fieldParentNameWithEndDot.slice(0, -1) - const fieldValidationErrors = []; + const fieldValidationErrors = [] const validatorContext = { - addValidationErrors(errors) { - errors.forEach((error) => fieldValidationErrors.push(error)); + addValidationErrors (errors) { + errors.forEach((error) => fieldValidationErrors.push(error)) }, - field(fName) { - return getFieldInfo(fName); + field (fName) { + return getFieldInfo(fName) }, genericKey: affectedKeyGeneric, isInArrayItemObject, @@ -109,39 +109,39 @@ function doValidation({ key: affectedKey, obj, operator: op, - parentField() { - return getFieldInfo(fieldParentName); + parentField () { + return getFieldInfo(fieldParentName) }, - siblingField(fName) { - return getFieldInfo(fieldParentNameWithEndDot + fName); + siblingField (fName) { + return getFieldInfo(fieldParentNameWithEndDot + fName) }, validationContext, value: val, // Value checks are not necessary for null or undefined values, except // for non-optional null array items, or for $unset or $rename values valueShouldBeChecked: ( - op !== '$unset' && op !== '$rename' - && ((val !== undefined && val !== null) || (affectedKeyGeneric.slice(-2) === '.$' && val === null && !def.optional)) + op !== '$unset' && op !== '$rename' && + ((val !== undefined && val !== null) || (affectedKeyGeneric.slice(-2) === '.$' && val === null && !def.optional)) ), - ...(extendedCustomContext || {}), - }; + ...(extendedCustomContext || {}) + } const builtInValidators = [ requiredValidator, typeValidator, - allowedValuesValidator, - ]; + allowedValuesValidator + ] const validators = builtInValidators .concat(schema._validators) - .concat(SimpleSchema._validators); + .concat(SimpleSchema._validators) // Loop through each of the definitions in the SimpleSchemaGroup. // If any return true, we're valid. const fieldIsValid = def.type.some((typeDef) => { // If the type is SimpleSchema.Any, then it is valid: - if (typeDef === SimpleSchema.Any) return true; + if (typeDef === SimpleSchema.Any) return true - const { type, ...definitionWithoutType } = def; // eslint-disable-line no-unused-vars + const { type, ...definitionWithoutType } = def // eslint-disable-line no-unused-vars const finalValidatorContext = { ...validatorContext, @@ -150,21 +150,21 @@ function doValidation({ // and add them to inner props like "type" and "min" definition: { ...definitionWithoutType, - ...typeDef, - }, - }; + ...typeDef + } + } // Add custom field validators to the list after the built-in // validators but before the schema and global validators. - const fieldValidators = validators.slice(0); + const fieldValidators = validators.slice(0) if (typeof typeDef.custom === 'function') { - fieldValidators.splice(builtInValidators.length, 0, typeDef.custom); + fieldValidators.splice(builtInValidators.length, 0, typeDef.custom) } // We use _.every just so that we don't continue running more validator // functions after the first one returns false or an error string. return fieldValidators.every((validator) => { - const result = validator.call(finalValidatorContext); + const result = validator.call(finalValidatorContext) // If the validator returns a string, assume it is the // error type. @@ -172,9 +172,9 @@ function doValidation({ fieldValidationErrors.push({ name: affectedKey, type: result, - value: val, - }); - return false; + value: val + }) + return false } // If the validator returns an object, assume it is an @@ -183,59 +183,59 @@ function doValidation({ fieldValidationErrors.push({ name: affectedKey, value: val, - ...result, - }); - return false; + ...result + }) + return false } // If the validator returns false, assume they already // called this.addValidationErrors within the function - if (result === false) return false; + if (result === false) return false // Any other return value we assume means it was valid - return true; - }); - }); + return true + }) + }) if (!fieldIsValid) { - validationErrors = validationErrors.concat(fieldValidationErrors); + validationErrors = validationErrors.concat(fieldValidationErrors) } } // The recursive function to iterate over the // potentially nested document structure - function checkObj({ + function checkObj ({ val, affectedKey, operator, isInArrayItemObject = false, - isInSubObject = false, + isInSubObject = false }) { - let affectedKeyGeneric; - let def; + let affectedKeyGeneric + let def if (affectedKey) { // When we hit a blackbox key, we don't progress any further - if (schema.keyIsInBlackBox(affectedKey)) return; + if (schema.keyIsInBlackBox(affectedKey)) return // Make a generic version of the affected key, and use that // to get the schema for this key. - affectedKeyGeneric = MongoObject.makeKeyGeneric(affectedKey); + affectedKeyGeneric = MongoObject.makeKeyGeneric(affectedKey) const shouldValidateKey = !keysToValidate || keysToValidate.some((keyToValidate) => ( - keyToValidate === affectedKey - || keyToValidate === affectedKeyGeneric - || affectedKey.startsWith(`${keyToValidate}.`) - || affectedKeyGeneric.startsWith(`${keyToValidate}.`) - )); + keyToValidate === affectedKey || + keyToValidate === affectedKeyGeneric || + affectedKey.startsWith(`${keyToValidate}.`) || + affectedKeyGeneric.startsWith(`${keyToValidate}.`) + )) // Prepare the context object for the rule functions - const fieldParentNameWithEndDot = getParentOfKey(affectedKey, true); - const fieldParentName = fieldParentNameWithEndDot.slice(0, -1); + const fieldParentNameWithEndDot = getParentOfKey(affectedKey, true) + const fieldParentName = fieldParentNameWithEndDot.slice(0, -1) const functionsContext = { - field(fName) { - return getFieldInfo(fName); + field (fName) { + return getFieldInfo(fName) }, genericKey: affectedKeyGeneric, isInArrayItemObject, @@ -245,33 +245,33 @@ function doValidation({ key: affectedKey, obj, operator, - parentField() { - return getFieldInfo(fieldParentName); + parentField () { + return getFieldInfo(fieldParentName) }, - siblingField(fName) { - return getFieldInfo(fieldParentNameWithEndDot + fName); + siblingField (fName) { + return getFieldInfo(fieldParentNameWithEndDot + fName) }, validationContext, value: val, - ...(extendedCustomContext || {}), - }; + ...(extendedCustomContext || {}) + } // Perform validation for this key - def = schema.getDefinition(affectedKey, null, functionsContext); + def = schema.getDefinition(affectedKey, null, functionsContext) if (shouldValidateKey) { - validate(val, affectedKey, affectedKeyGeneric, def, operator, isInArrayItemObject, isInSubObject); + validate(val, affectedKey, affectedKeyGeneric, def, operator, isInArrayItemObject, isInSubObject) } } // If affectedKeyGeneric is undefined due to this being the first run of this // function, objectKeys will return the top-level keys. - const childKeys = schema.objectKeys(affectedKeyGeneric); + const childKeys = schema.objectKeys(affectedKeyGeneric) // Temporarily convert missing objects to empty objects // so that the looping code will be called and required // descendent keys can be validated. if ((val === undefined || val === null) && (!def || (!def.optional && childKeys && childKeys.length > 0))) { - val = {}; + val = {} } // Loop through arrays @@ -280,20 +280,20 @@ function doValidation({ checkObj({ val: v, affectedKey: `${affectedKey}.${i}`, - operator, - }); - }); + operator + }) + }) } else if (isObjectWeShouldTraverse(val) && (!def || !schema._blackboxKeys.has(affectedKey))) { // Loop through object keys // Get list of present keys - const presentKeys = Object.keys(val); + const presentKeys = Object.keys(val) // If this object is within an array, make sure we check for // required as if it's not a modifier - isInArrayItemObject = (affectedKeyGeneric && affectedKeyGeneric.slice(-2) === '.$'); + isInArrayItemObject = (affectedKeyGeneric && affectedKeyGeneric.slice(-2) === '.$') - const checkedKeys = []; + const checkedKeys = [] // Check all present keys plus all keys defined by the schema. // This allows us to detect extra keys not allowed by the schema plus @@ -302,74 +302,74 @@ function doValidation({ for (const key of [...presentKeys, ...childKeys]) { // `childKeys` and `presentKeys` may contain the same keys, so make // sure we run only once per unique key - if (checkedKeys.indexOf(key) !== -1) continue; - checkedKeys.push(key); + if (checkedKeys.indexOf(key) !== -1) continue + checkedKeys.push(key) checkObj({ val: val[key], affectedKey: appendAffectedKey(affectedKey, key), operator, isInArrayItemObject, - isInSubObject: true, - }); + isInSubObject: true + }) } /* eslint-enable no-restricted-syntax */ } } - function checkModifier(mod) { + function checkModifier (mod) { // Loop through operators Object.keys(mod).forEach((op) => { - const opObj = mod[op]; + const opObj = mod[op] // If non-operators are mixed in, throw error if (op.slice(0, 1) !== '$') { - throw new Error(`Expected '${op}' to be a modifier operator like '$set'`); + throw new Error(`Expected '${op}' to be a modifier operator like '$set'`) } if (shouldCheck(op)) { // For an upsert, missing props would not be set if an insert is performed, // so we check them all with undefined value to force any 'required' checks to fail if (isUpsert && (op === '$set' || op === '$setOnInsert')) { - const presentKeys = Object.keys(opObj); + const presentKeys = Object.keys(opObj) schema.objectKeys().forEach((schemaKey) => { if (!presentKeys.includes(schemaKey)) { checkObj({ val: undefined, affectedKey: schemaKey, - operator: op, - }); + operator: op + }) } - }); + }) } // Don't use forEach here because it will not properly handle an // object that has a property named `length` Object.keys(opObj).forEach((k) => { - let v = opObj[k]; + let v = opObj[k] if (op === '$push' || op === '$addToSet') { if (typeof v === 'object' && '$each' in v) { - v = v.$each; + v = v.$each } else { - k = `${k}.0`; + k = `${k}.0` } } checkObj({ val: v, affectedKey: k, - operator: op, - }); - }); + operator: op + }) + }) } - }); + }) } // Kick off the validation if (isModifier) { - checkModifier(obj); + checkModifier(obj) } else { - checkObj({ val: obj }); + checkObj({ val: obj }) } // Custom whole-doc validators - const docValidators = schema._docValidators.concat(SimpleSchema._docValidators); + const docValidators = schema._docValidators.concat(SimpleSchema._docValidators) const docValidatorContext = { ignoreTypes, isModifier, @@ -379,25 +379,25 @@ function doValidation({ obj, schema, validationContext, - ...(extendedCustomContext || {}), - }; + ...(extendedCustomContext || {}) + } docValidators.forEach((func) => { - const errors = func.call(docValidatorContext, obj); - if (!Array.isArray(errors)) throw new Error('Custom doc validator must return an array of error objects'); - if (errors.length) validationErrors = validationErrors.concat(errors); - }); + const errors = func.call(docValidatorContext, obj) + if (!Array.isArray(errors)) throw new Error('Custom doc validator must return an array of error objects') + if (errors.length) validationErrors = validationErrors.concat(errors) + }) - const addedFieldNames = []; + const addedFieldNames = [] validationErrors = validationErrors.filter((errObj) => { // Remove error types the user doesn't care about - if (ignoreTypes.includes(errObj.type)) return false; + if (ignoreTypes.includes(errObj.type)) return false // Make sure there is only one error per fieldName - if (addedFieldNames.includes(errObj.name)) return false; + if (addedFieldNames.includes(errObj.name)) return false - addedFieldNames.push(errObj.name); - return true; - }); - return validationErrors; + addedFieldNames.push(errObj.name) + return true + }) + return validationErrors } -export default doValidation; +export default doValidation diff --git a/lib/expandShorthand.js b/lib/expandShorthand.js index 327be4d..fef3da0 100644 --- a/lib/expandShorthand.js +++ b/lib/expandShorthand.js @@ -1,55 +1,55 @@ -import MongoObject from 'mongo-object'; +import MongoObject from 'mongo-object' /** * Clones a schema object, expanding shorthand as it does it. */ -function expandShorthand(schema) { - const schemaClone = {}; +function expandShorthand (schema) { + const schemaClone = {} Object.keys(schema).forEach((key) => { - const definition = schema[key]; + const definition = schema[key] // CASE 1: Not shorthand. Just clone if (MongoObject.isBasicObject(definition)) { - schemaClone[key] = { ...definition }; - return; + schemaClone[key] = { ...definition } + return } // CASE 2: The definition is an array of some type if (Array.isArray(definition)) { if (Array.isArray(definition[0])) { - throw new Error(`Array shorthand may only be used to one level of depth (${key})`); + throw new Error(`Array shorthand may only be used to one level of depth (${key})`) } - const type = definition[0]; - schemaClone[key] = { type: Array }; + const type = definition[0] + schemaClone[key] = { type: Array } // Also add the item key definition - const itemKey = `${key}.$`; + const itemKey = `${key}.$` if (schema[itemKey]) { - throw new Error(`Array shorthand used for ${key} field but ${key}.$ key is already in the schema`); + throw new Error(`Array shorthand used for ${key} field but ${key}.$ key is already in the schema`) } if (type instanceof RegExp) { - schemaClone[itemKey] = { type: String, regEx: type }; + schemaClone[itemKey] = { type: String, regEx: type } } else { - schemaClone[itemKey] = { type }; + schemaClone[itemKey] = { type } } - return; + return } // CASE 3: The definition is a regular expression if (definition instanceof RegExp) { schemaClone[key] = { type: String, - regEx: definition, - }; - return; + regEx: definition + } + return } // CASE 4: The definition is something, a type - schemaClone[key] = { type: definition }; - }); + schemaClone[key] = { type: definition } + }) - return schemaClone; + return schemaClone } -export default expandShorthand; +export default expandShorthand diff --git a/lib/expandShorthand.tests.js b/lib/expandShorthand.tests.js index 0cdc4ef..c1f0fb2 100644 --- a/lib/expandShorthand.tests.js +++ b/lib/expandShorthand.tests.js @@ -1,49 +1,49 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import expandShorthand from './expandShorthand'; +import { expect } from 'chai' +import expandShorthand from './expandShorthand' describe('expandShorthand', function () { it('test 1', function () { const result = expandShorthand({ name: String, count: Number, - exp: /foo/, - }); + exp: /foo/ + }) expect(result).to.deep.equal({ name: { - type: String, + type: String }, count: { - type: Number, + type: Number }, exp: { type: String, - regEx: /foo/, - }, - }); - }); + regEx: /foo/ + } + }) + }) it('test 2', function () { const result = expandShorthand({ name: [String], - count: [Number], - }); + count: [Number] + }) expect(result).to.deep.equal({ name: { - type: Array, + type: Array }, 'name.$': { - type: String, + type: String }, count: { - type: Array, + type: Array }, 'count.$': { - type: Number, - }, - }); - }); -}); + type: Number + } + }) + }) +}) diff --git a/lib/humanize.js b/lib/humanize.js index b3ea781..7f56953 100644 --- a/lib/humanize.js +++ b/lib/humanize.js @@ -4,47 +4,47 @@ https://github.com/jxson/string-capitalize */ -function capitalize(text) { - text = text || ''; - text = text.trim(); +function capitalize (text) { + text = text || '' + text = text.trim() if (text[0]) { - text = text[0].toUpperCase() + text.substr(1).toLowerCase(); + text = text[0].toUpperCase() + text.substr(1).toLowerCase() } // Do "ID" instead of "id" or "Id" - text = text.replace(/\bid\b/g, 'ID'); - text = text.replace(/\bId\b/g, 'ID'); + text = text.replace(/\bid\b/g, 'ID') + text = text.replace(/\bId\b/g, 'ID') - return text; + return text } -function underscore(text) { - text = text || ''; - text = text.toString(); // might be a number - text = text.trim(); - text = text.replace(/([a-z\d])([A-Z]+)/g, '$1_$2'); - text = text.replace(/[-\s]+/g, '_').toLowerCase(); +function underscore (text) { + text = text || '' + text = text.toString() // might be a number + text = text.trim() + text = text.replace(/([a-z\d])([A-Z]+)/g, '$1_$2') + text = text.replace(/[-\s]+/g, '_').toLowerCase() - return text; + return text } -function extname(text) { - const index = text.lastIndexOf('.'); - const ext = text.substring(index, text.length); +function extname (text) { + const index = text.lastIndexOf('.') + const ext = text.substring(index, text.length) - return (index === -1) ? '' : ext; + return (index === -1) ? '' : ext } -function humanize(text) { - text = text || ''; - text = text.toString(); // might be a number - text = text.trim(); - text = text.replace(extname(text), ''); - text = underscore(text); - text = text.replace(/[\W_]+/g, ' '); +function humanize (text) { + text = text || '' + text = text.toString() // might be a number + text = text.trim() + text = text.replace(extname(text), '') + text = underscore(text) + text = text.replace(/[\W_]+/g, ' ') - return capitalize(text); + return capitalize(text) } -export default humanize; +export default humanize diff --git a/lib/humanize.tests.js b/lib/humanize.tests.js index a93ff21..72d76cd 100644 --- a/lib/humanize.tests.js +++ b/lib/humanize.tests.js @@ -1,25 +1,25 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import humanize from './humanize'; +import { expect } from 'chai' +import humanize from './humanize' describe('humanize', function () { it('works', function () { - expect(humanize('super_snake_case')).to.equal('Super snake case'); - expect(humanize('capitalizedCamelCase')).to.equal('Capitalized camel case'); - expect(humanize('hyphen-case')).to.equal('Hyphen case'); - expect(humanize('no-extensions-here.md')).to.equal('No extensions here'); - expect(humanize('lower cased phrase')).to.equal('Lower cased phrase'); - expect(humanize(' so many spaces ')).to.equal('So many spaces'); - expect(humanize(123)).to.equal('123'); - expect(humanize('')).to.equal(''); - expect(humanize(null)).to.equal(''); - expect(humanize(undefined)).to.equal(''); - expect(humanize('externalSource')).to.equal('External source'); - expect(humanize('externalSourceId')).to.equal('External source ID'); - expect(humanize('externalSource_id')).to.equal('External source ID'); - expect(humanize('_id')).to.equal('ID'); + expect(humanize('super_snake_case')).to.equal('Super snake case') + expect(humanize('capitalizedCamelCase')).to.equal('Capitalized camel case') + expect(humanize('hyphen-case')).to.equal('Hyphen case') + expect(humanize('no-extensions-here.md')).to.equal('No extensions here') + expect(humanize('lower cased phrase')).to.equal('Lower cased phrase') + expect(humanize(' so many spaces ')).to.equal('So many spaces') + expect(humanize(123)).to.equal('123') + expect(humanize('')).to.equal('') + expect(humanize(null)).to.equal('') + expect(humanize(undefined)).to.equal('') + expect(humanize('externalSource')).to.equal('External source') + expect(humanize('externalSourceId')).to.equal('External source ID') + expect(humanize('externalSource_id')).to.equal('External source ID') + expect(humanize('_id')).to.equal('ID') // Make sure it does not mess with "id" in the middle of a word - expect(humanize('overridden')).to.equal('Overridden'); - }); -}); + expect(humanize('overridden')).to.equal('Overridden') + }) +}) diff --git a/lib/main.js b/lib/main.js index 6c5faff..2882ee4 100644 --- a/lib/main.js +++ b/lib/main.js @@ -1,6 +1,6 @@ -import { SimpleSchema, ValidationContext } from './SimpleSchema'; -import './clean'; +import { SimpleSchema, ValidationContext } from './SimpleSchema' +import './clean' -SimpleSchema.ValidationContext = ValidationContext; +SimpleSchema.ValidationContext = ValidationContext -export default SimpleSchema; +export default SimpleSchema diff --git a/lib/reactivity.tests.js b/lib/reactivity.tests.js index fc71c32..3a1a264 100644 --- a/lib/reactivity.tests.js +++ b/lib/reactivity.tests.js @@ -1,71 +1,71 @@ -import { expect } from 'chai'; -import { SimpleSchema } from './SimpleSchema'; -import { Tracker } from 'meteor/tracker'; +import { expect } from 'chai' +import { SimpleSchema } from './SimpleSchema' +import { Tracker } from 'meteor/tracker' it('Tracker reactivity works for labels', function (done) { const schema = new SimpleSchema({ foo: { type: String, - label: 'First', - }, - }, { tracker: Tracker }); + label: 'First' + } + }, { tracker: Tracker }) - const labelResults = []; - function checkResults() { + const labelResults = [] + function checkResults () { expect(labelResults).to.deep.equal([ 'First', - 'Second', - ]); - done(); + 'Second' + ]) + done() } - Tracker.autorun(function autorun() { - labelResults.push(schema.label('foo')); - if (labelResults.length === 2) checkResults(); - }); + Tracker.autorun(function autorun () { + labelResults.push(schema.label('foo')) + if (labelResults.length === 2) checkResults() + }) - schema.labels({ foo: 'Second' }); -}); + schema.labels({ foo: 'Second' }) +}) it('Tracker reactivity works for labels in subschemas', function (done) { const subSchema = new SimpleSchema({ foo: { type: String, - label: 'First', - }, - }); + label: 'First' + } + }) const schema = new SimpleSchema({ - sub: subSchema, - }, { tracker: Tracker }); + sub: subSchema + }, { tracker: Tracker }) - const labelResults = []; - function checkResults() { + const labelResults = [] + function checkResults () { expect(labelResults).to.deep.equal([ 'First', - 'Second', - ]); - done(); + 'Second' + ]) + done() } - Tracker.autorun(function autorun() { - labelResults.push(schema.label('sub.foo')); - if (labelResults.length === 2) checkResults(); - }); + Tracker.autorun(function autorun () { + labelResults.push(schema.label('sub.foo')) + if (labelResults.length === 2) checkResults() + }) - subSchema.labels({ foo: 'Second' }); -}); + subSchema.labels({ foo: 'Second' }) +}) it('Tracker reactivity works for error messages', function (done) { const schema = new SimpleSchema({ foo: { type: String, - label: 'First', - }, - }, { tracker: Tracker }); + label: 'First' + } + }, { tracker: Tracker }) - const errorResults = []; - function checkResults() { + const errorResults = [] + function checkResults () { expect(errorResults).to.deep.equal([ [], [ @@ -74,33 +74,33 @@ it('Tracker reactivity works for error messages', function (done) { type: 'required', value: undefined } - ], - ]); - done(); + ] + ]) + done() } - Tracker.autorun(function autorun() { - errorResults.push(schema.namedContext().validationErrors()); - if (errorResults.length === 2) checkResults(); - }); + Tracker.autorun(function autorun () { + errorResults.push(schema.namedContext().validationErrors()) + if (errorResults.length === 2) checkResults() + }) - schema.namedContext().validate({}); -}); + schema.namedContext().validate({}) +}) it('Tracker reactivity works for error messages in subschemas', function (done) { const subSchema = new SimpleSchema({ foo: { type: String, - label: 'First', - }, - }); + label: 'First' + } + }) const schema = new SimpleSchema({ - sub: subSchema, - }, { tracker: Tracker }); + sub: subSchema + }, { tracker: Tracker }) - const errorResults = []; - function checkResults() { + const errorResults = [] + function checkResults () { expect(errorResults).to.deep.equal([ [], [ @@ -114,15 +114,15 @@ it('Tracker reactivity works for error messages in subschemas', function (done) type: 'required', value: undefined } - ], - ]); - done(); + ] + ]) + done() } - Tracker.autorun(function autorun() { - errorResults.push(schema.namedContext().validationErrors()); - if (errorResults.length === 2) checkResults(); - }); + Tracker.autorun(function autorun () { + errorResults.push(schema.namedContext().validationErrors()) + if (errorResults.length === 2) checkResults() + }) - schema.namedContext().validate({}); -}); + schema.namedContext().validate({}) +}) diff --git a/lib/regExp.js b/lib/regExp.js index a0f54b9..0a5ae7e 100644 --- a/lib/regExp.js +++ b/lib/regExp.js @@ -2,18 +2,19 @@ // sadly IPv4 Adresses will be caught too but technically those are valid domains // this expression is extracted from the original RFC 5322 mail expression // a modification enforces that the tld consists only of characters -const rxDomain = '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z](?:[a-z-]*[a-z])?'; +const rxDomain = '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z](?:[a-z-]*[a-z])?' // this domain regex matches everythign that could be a domain in intranet // that means "localhost" is a valid domain -const rxNameDomain = '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.|$))+'; +const rxNameDomain = '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.|$))+' // strict IPv4 expression which allows 0-255 per oktett -const rxIPv4 = '(?:(?:[0-1]?\\d{1,2}|2[0-4]\\d|25[0-5])(?:\\.|$)){4}'; +const rxIPv4 = '(?:(?:[0-1]?\\d{1,2}|2[0-4]\\d|25[0-5])(?:\\.|$)){4}' // strict IPv6 expression which allows (and validates) all shortcuts -const rxIPv6 = '(?:(?:[\\dA-Fa-f]{1,4}(?::|$)){8}' // full adress - + '|(?=(?:[^:\\s]|:[^:\\s])*::(?:[^:\\s]|:[^:\\s])*$)' // or min/max one '::' - + '[\\dA-Fa-f]{0,4}(?:::?(?:[\\dA-Fa-f]{1,4}|$)){1,6})'; // and short adress +const rxIPv6 = + '(?:(?:[\\dA-Fa-f]{1,4}(?::|$)){8}' + // full adress + '|(?=(?:[^:\\s]|:[^:\\s])*::(?:[^:\\s]|:[^:\\s])*$)' + // or min/max one '::' + '[\\dA-Fa-f]{0,4}(?:::?(?:[\\dA-Fa-f]{1,4}|$)){1,6})' // and short adress // this allows domains (also localhost etc) and ip adresses -const rxWeakDomain = `(?:${[rxNameDomain, rxIPv4, rxIPv6].join('|')})`; +const rxWeakDomain = `(?:${[rxNameDomain, rxIPv4, rxIPv6].join('|')})` // unique id from the random package also used by minimongo // min and max are used to set length boundaries // set both for explicit lower and upper bounds @@ -22,26 +23,28 @@ const rxWeakDomain = `(?:${[rxNameDomain, rxIPv4, rxIPv6].join('|')})`; // set only min for fixed length // character list: https://github.com/meteor/meteor/blob/release/0.8.0/packages/random/random.js#L88 // string length: https://github.com/meteor/meteor/blob/release/0.8.0/packages/random/random.js#L143 -const isValidBound = (value, lower) => !value || (Number.isSafeInteger(value) && value > lower); +const isValidBound = (value, lower) => !value || (Number.isSafeInteger(value) && value > lower) const idOfLength = (min, max) => { - if (!isValidBound(min, 0)) throw new Error(`Expected a non-negative safe integer, got ${min}`); - if (!isValidBound(max, min)) throw new Error(`Expected a non-negative safe integer greater than 1 and greater than min, got ${max}`); - let bounds; - if (min && max) bounds = `${min},${max}`; - else if (min && max === null) bounds = `${min},`; - else if (min && !max) bounds = `${min}`; - else if (!min && !max) bounds = '0,'; - else throw new Error(`Unexpected state for min (${min}) and max (${max})`); - return new RegExp(`^[23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz]{${bounds}}$`); -}; + if (!isValidBound(min, 0)) throw new Error(`Expected a non-negative safe integer, got ${min}`) + if (!isValidBound(max, min)) throw new Error(`Expected a non-negative safe integer greater than 1 and greater than min, got ${max}`) + let bounds + if (min && max) bounds = `${min},${max}` + else if (min && max === null) bounds = `${min},` + else if (min && !max) bounds = `${min}` + else if (!min && !max) bounds = '0,' + else throw new Error(`Unexpected state for min (${min}) and max (${max})`) + return new RegExp(`^[23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz]{${bounds}}$`) +} const regEx = { // We use the RegExp suggested by W3C in http://www.w3.org/TR/html5/forms.html#valid-e-mail-address // This is probably the same logic used by most browsers when type=email, which is our goal. It is // a very permissive expression. Some apps may wish to be more strict and can write their own RegExp. + // eslint-disable-next-line no-useless-escape Email: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, // Like Email but requires the TLD (.com, etc) + // eslint-disable-next-line no-useless-escape EmailWithTLD: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, Domain: new RegExp(`^${rxDomain}$`), @@ -61,7 +64,6 @@ const regEx = { // return 'badUrl'; // } // } - // eslint-disable-next-line redos/no-vulnerable Url: /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i, // default id is defined with exact 17 chars of length Id: idOfLength(17), @@ -76,8 +78,8 @@ const regEx = { // DEPRECATED! Known 2nd degree polynomial ReDoS vulnerability. // Instead, use a custom validation function, with a high quality // phone number validation package that meets your needs. - // eslint-disable-next-line redos/no-vulnerable - Phone: /^[0-90-9٠-٩۰-۹]{2}$|^[++]*(?:[-x‐-―−ー--/ ­​⁠ ()()[].\[\]/~⁓∼~*]*[0-90-9٠-٩۰-۹]){3,}[-x‐-―−ー--/ ­​⁠ ()()[].\[\]/~⁓∼~*A-Za-z0-90-9٠-٩۰-۹]*(?:;ext=([0-90-9٠-٩۰-۹]{1,20})|[ \t,]*(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|доб|anexo)[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,20})#?|[ \t,]*(?:[xx##~~]|int|int)[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,9})#?|[- ]+([0-90-9٠-٩۰-۹]{1,6})#|[ \t]*(?:,{2}|;)[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,15})#?|[ \t]*(?:,)+[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,9})#?)?$/i, // eslint-disable-line no-irregular-whitespace -}; + // eslint-disable-next-line no-useless-escape + Phone: /^[0-90-9٠-٩۰-۹]{2}$|^[++]*(?:[-x‐-―−ー--/ ­​⁠ ()()[].\[\]/~⁓∼~*]*[0-90-9٠-٩۰-۹]){3,}[-x‐-―−ー--/ ­​⁠ ()()[].\[\]/~⁓∼~*A-Za-z0-90-9٠-٩۰-۹]*(?:;ext=([0-90-9٠-٩۰-۹]{1,20})|[ \t,]*(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|доб|anexo)[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,20})#?|[ \t,]*(?:[xx##~~]|int|int)[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,9})#?|[- ]+([0-90-9٠-٩۰-۹]{1,6})#|[ \t]*(?:,{2}|;)[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,15})#?|[ \t]*(?:,)+[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,9})#?)?$/i // eslint-disable-line no-irregular-whitespace +} -export default regEx; +export default regEx diff --git a/lib/testHelpers/Address.js b/lib/testHelpers/Address.js index d5dbe20..f686748 100644 --- a/lib/testHelpers/Address.js +++ b/lib/testHelpers/Address.js @@ -1,34 +1,34 @@ class Address { - constructor(city, state) { - this.city = city; - this.state = state; + constructor (city, state) { + this.city = city + this.state = state } - toString() { - return `${this.city}, ${this.state}`; + toString () { + return `${this.city}, ${this.state}` } - clone() { - return new Address(this.city, this.state); + clone () { + return new Address(this.city, this.state) } - equals(other) { + equals (other) { if (!(other instanceof Address)) { - return false; + return false } - return JSON.stringify(this) === JSON.stringify(other); + return JSON.stringify(this) === JSON.stringify(other) } - typeName() { // eslint-disable-line class-methods-use-this - return 'Address'; + typeName () { // eslint-disable-line class-methods-use-this + return 'Address' } - toJSONValue() { + toJSONValue () { return { city: this.city, - state: this.state, - }; + state: this.state + } } } -export default Address; +export default Address diff --git a/lib/testHelpers/expectErrorLength.js b/lib/testHelpers/expectErrorLength.js index c96f28f..9397c6d 100644 --- a/lib/testHelpers/expectErrorLength.js +++ b/lib/testHelpers/expectErrorLength.js @@ -1,6 +1,6 @@ -import { expect } from 'chai'; -import validate from './validate'; +import { expect } from 'chai' +import validate from './validate' -export default function expectErrorLength(...args) { - return expect(validate(...args).validationErrors().length); +export default function expectErrorLength (...args) { + return expect(validate(...args).validationErrors().length) } diff --git a/lib/testHelpers/expectErrorOfTypeLength.js b/lib/testHelpers/expectErrorOfTypeLength.js index 60e0090..d32842c 100644 --- a/lib/testHelpers/expectErrorOfTypeLength.js +++ b/lib/testHelpers/expectErrorOfTypeLength.js @@ -1,12 +1,12 @@ -import { expect } from 'chai'; -import validate from './validate'; +import { expect } from 'chai' +import validate from './validate' -export default function expectErrorOfTypeLength(type, ...args) { - const errors = validate(...args).validationErrors(); +export default function expectErrorOfTypeLength (type, ...args) { + const errors = validate(...args).validationErrors() - let errorCount = 0; + let errorCount = 0 errors.forEach((error) => { - if (error.type === type) errorCount++; - }); - return expect(errorCount); + if (error.type === type) errorCount++ + }) + return expect(errorCount) } diff --git a/lib/testHelpers/expectRequiredErrorLength.js b/lib/testHelpers/expectRequiredErrorLength.js index fe7ef5a..168d7e3 100644 --- a/lib/testHelpers/expectRequiredErrorLength.js +++ b/lib/testHelpers/expectRequiredErrorLength.js @@ -1,13 +1,13 @@ -import { expect } from 'chai'; -import validate from './validate'; -import { SimpleSchema } from '../SimpleSchema'; +import { expect } from 'chai' +import validate from './validate' +import { SimpleSchema } from '../SimpleSchema' -export default function expectRequiredErrorLength(...args) { - const errors = validate(...args).validationErrors(); +export default function expectRequiredErrorLength (...args) { + const errors = validate(...args).validationErrors() - let requiredErrorCount = 0; + let requiredErrorCount = 0 errors.forEach((error) => { - if (error.type === SimpleSchema.ErrorTypes.REQUIRED) requiredErrorCount++; - }); - return expect(requiredErrorCount); + if (error.type === SimpleSchema.ErrorTypes.REQUIRED) requiredErrorCount++ + }) + return expect(requiredErrorCount) } diff --git a/lib/testHelpers/expectValid.js b/lib/testHelpers/expectValid.js index 12cd560..b4a2399 100644 --- a/lib/testHelpers/expectValid.js +++ b/lib/testHelpers/expectValid.js @@ -1,6 +1,6 @@ -import { expect } from 'chai'; -import validate from './validate'; +import { expect } from 'chai' +import validate from './validate' -export default function expectValid(...args) { - expect(validate(...args).isValid()).to.equal(true); +export default function expectValid (...args) { + expect(validate(...args).isValid()).to.equal(true) } diff --git a/lib/testHelpers/friendsSchema.js b/lib/testHelpers/friendsSchema.js index 99c8b5e..0a821fa 100644 --- a/lib/testHelpers/friendsSchema.js +++ b/lib/testHelpers/friendsSchema.js @@ -1,55 +1,55 @@ -import { SimpleSchema } from '../SimpleSchema'; +import { SimpleSchema } from '../SimpleSchema' const friendsSchema = new SimpleSchema({ name: { type: String, - optional: true, + optional: true }, friends: { type: Array, - minCount: 1, + minCount: 1 }, 'friends.$': { - type: Object, + type: Object }, 'friends.$.name': { type: String, - max: 3, + max: 3 }, 'friends.$.type': { type: String, - allowedValues: ['best', 'good', 'bad'], + allowedValues: ['best', 'good', 'bad'] }, 'friends.$.a': { type: Object, - optional: true, + optional: true }, 'friends.$.a.b': { type: SimpleSchema.Integer, - optional: true, + optional: true }, enemies: { - type: Array, + type: Array }, 'enemies.$': { - type: Object, + type: Object }, 'enemies.$.name': { - type: String, + type: String }, 'enemies.$.traits': { type: Array, - optional: true, + optional: true }, 'enemies.$.traits.$': { - type: Object, + type: Object }, 'enemies.$.traits.$.name': { - type: String, + type: String }, 'enemies.$.traits.$.weight': { - type: Number, - }, -}); + type: Number + } +}) -export default friendsSchema; +export default friendsSchema diff --git a/lib/testHelpers/optionalCustomSchema.js b/lib/testHelpers/optionalCustomSchema.js index 56de549..9df182c 100644 --- a/lib/testHelpers/optionalCustomSchema.js +++ b/lib/testHelpers/optionalCustomSchema.js @@ -1,11 +1,11 @@ -import { SimpleSchema } from '../SimpleSchema'; +import { SimpleSchema } from '../SimpleSchema' const optionalCustomSchema = new SimpleSchema({ foo: { type: String, optional: true, - custom: () => 'custom', - }, -}); + custom: () => 'custom' + } +}) -export default optionalCustomSchema; +export default optionalCustomSchema diff --git a/lib/testHelpers/requiredCustomSchema.js b/lib/testHelpers/requiredCustomSchema.js index 8dbf926..53f7a28 100644 --- a/lib/testHelpers/requiredCustomSchema.js +++ b/lib/testHelpers/requiredCustomSchema.js @@ -1,30 +1,30 @@ -import { SimpleSchema } from '../SimpleSchema'; +import { SimpleSchema } from '../SimpleSchema' const requiredCustomSchema = new SimpleSchema({ a: { type: Array, - custom() { + custom () { // Just adding custom to trigger extra validation - }, + } }, 'a.$': { type: Object, - custom() { + custom () { // Just adding custom to trigger extra validation - }, + } }, b: { type: Array, - custom() { + custom () { // Just adding custom to trigger extra validation - }, + } }, 'b.$': { type: Object, - custom() { + custom () { // Just adding custom to trigger extra validation - }, - }, -}); + } + } +}) -export default requiredCustomSchema; +export default requiredCustomSchema diff --git a/lib/testHelpers/requiredSchema.js b/lib/testHelpers/requiredSchema.js index 08b4522..b17aad2 100644 --- a/lib/testHelpers/requiredSchema.js +++ b/lib/testHelpers/requiredSchema.js @@ -1,56 +1,56 @@ -import { SimpleSchema } from '../SimpleSchema'; +import { SimpleSchema } from '../SimpleSchema' const requiredSchema = new SimpleSchema({ requiredString: { - type: String, + type: String }, requiredBoolean: { - type: Boolean, + type: Boolean }, requiredNumber: { - type: SimpleSchema.Integer, + type: SimpleSchema.Integer }, requiredDate: { - type: Date, + type: Date }, requiredEmail: { type: String, - regEx: SimpleSchema.RegEx.Email, + regEx: SimpleSchema.RegEx.Email }, requiredUrl: { type: String, - custom() { - if (!this.isSet) return; + custom () { + if (!this.isSet) return try { new URL(this.value); // eslint-disable-line } catch (err) { - return 'badUrl'; + return 'badUrl' } - }, + } }, requiredObject: { - type: Object, + type: Object }, 'requiredObject.requiredNumber': { - type: SimpleSchema.Integer, + type: SimpleSchema.Integer }, optionalObject: { type: Object, - optional: true, + optional: true }, 'optionalObject.requiredString': { - type: String, + type: String }, anOptionalOne: { type: String, optional: true, - min: 20, - }, -}); + min: 20 + } +}) requiredSchema.messageBox.messages({ 'regEx requiredEmail': '[label] is not a valid email address', - 'regEx requiredUrl': '[label] is not a valid URL', -}); + 'regEx requiredUrl': '[label] is not a valid URL' +}) -export default requiredSchema; +export default requiredSchema diff --git a/lib/testHelpers/testSchema.js b/lib/testHelpers/testSchema.js index d57b054..9a0d0af 100644 --- a/lib/testHelpers/testSchema.js +++ b/lib/testHelpers/testSchema.js @@ -1,109 +1,109 @@ -import { SimpleSchema } from '../SimpleSchema'; -import Address from './Address'; +import { SimpleSchema } from '../SimpleSchema' +import Address from './Address' const refSchema = new SimpleSchema({ string: { type: String, - optional: true, + optional: true }, number: { type: Number, - optional: true, - }, -}); + optional: true + } +}) const testSchema = new SimpleSchema({ string: { type: String, - optional: true, + optional: true }, minMaxString: { type: String, optional: true, min: 10, max: 20, - regEx: /^[a-z0-9_]+$/, + regEx: /^[a-z0-9_]+$/ }, minMaxStringArray: { type: Array, optional: true, minCount: 1, - maxCount: 2, + maxCount: 2 }, 'minMaxStringArray.$': { type: String, min: 10, - max: 20, + max: 20 }, allowedStrings: { type: String, optional: true, - allowedValues: ['tuna', 'fish', 'salad'], + allowedValues: ['tuna', 'fish', 'salad'] }, allowedStringsArray: { type: Array, - optional: true, + optional: true }, 'allowedStringsArray.$': { type: String, - allowedValues: ['tuna', 'fish', 'salad'], + allowedValues: ['tuna', 'fish', 'salad'] }, allowedStringsSet: { type: Array, - optional: true, + optional: true }, 'allowedStringsSet.$': { type: String, - allowedValues: new Set(['tuna', 'fish', 'salad']), + allowedValues: new Set(['tuna', 'fish', 'salad']) }, boolean: { type: Boolean, - optional: true, + optional: true }, booleanArray: { type: Array, - optional: true, + optional: true }, 'booleanArray.$': { - type: Boolean, + type: Boolean }, number: { type: SimpleSchema.Integer, - optional: true, + optional: true }, sub: { type: Object, - optional: true, + optional: true }, 'sub.number': { type: SimpleSchema.Integer, - optional: true, + optional: true }, minMaxNumber: { type: SimpleSchema.Integer, optional: true, min: 10, - max: 20, + max: 20 }, minZero: { type: SimpleSchema.Integer, optional: true, - min: 0, + min: 0 }, maxZero: { type: SimpleSchema.Integer, optional: true, - max: 0, + max: 0 }, minMaxNumberCalculated: { type: SimpleSchema.Integer, optional: true, - min() { - return 10; - }, - max() { - return 20; + min () { + return 10 }, + max () { + return 20 + } }, minMaxNumberExclusive: { type: SimpleSchema.Integer, @@ -111,7 +111,7 @@ const testSchema = new SimpleSchema({ min: 10, max: 20, exclusiveMax: true, - exclusiveMin: true, + exclusiveMin: true }, minMaxNumberInclusive: { type: SimpleSchema.Integer, @@ -119,113 +119,113 @@ const testSchema = new SimpleSchema({ min: 10, max: 20, exclusiveMax: false, - exclusiveMin: false, + exclusiveMin: false }, allowedNumbers: { type: SimpleSchema.Integer, optional: true, - allowedValues: [1, 2, 3], + allowedValues: [1, 2, 3] }, allowedNumbersArray: { type: Array, - optional: true, + optional: true }, 'allowedNumbersArray.$': { type: SimpleSchema.Integer, - allowedValues: [1, 2, 3], + allowedValues: [1, 2, 3] }, allowedNumbersSet: { type: Array, - optional: true, + optional: true }, 'allowedNumbersSet.$': { type: SimpleSchema.Integer, - allowedValues: new Set([1, 2, 3]), + allowedValues: new Set([1, 2, 3]) }, decimal: { type: Number, - optional: true, + optional: true }, date: { type: Date, - optional: true, + optional: true }, dateArray: { type: Array, - optional: true, + optional: true }, 'dateArray.$': { - type: Date, + type: Date }, minMaxDate: { type: Date, optional: true, min: (new Date(Date.UTC(2013, 0, 1))), - max: (new Date(Date.UTC(2013, 11, 31))), + max: (new Date(Date.UTC(2013, 11, 31))) }, minMaxDateCalculated: { type: Date, optional: true, - min() { - return (new Date(Date.UTC(2013, 0, 1))); - }, - max() { - return (new Date(Date.UTC(2013, 11, 31))); + min () { + return (new Date(Date.UTC(2013, 0, 1))) }, + max () { + return (new Date(Date.UTC(2013, 11, 31))) + } }, email: { type: String, regEx: SimpleSchema.RegEx.Email, - optional: true, + optional: true }, url: { type: String, optional: true, - custom() { - if (!this.isSet) return; + custom () { + if (!this.isSet) return try { new URL(this.value); // eslint-disable-line } catch (err) { - return 'badUrl'; + return 'badUrl' } - }, + } }, customObject: { type: Address, optional: true, - blackbox: true, + blackbox: true }, blackBoxObject: { type: Object, optional: true, - blackbox: true, + blackbox: true }, objectArray: { type: Array, - optional: true, + optional: true }, 'objectArray.$': { type: Object, - optional: true, + optional: true }, refObject: { type: refSchema, - optional: true, + optional: true }, refSchemaArray: { type: Array, - optional: true, + optional: true }, 'refSchemaArray.$': { type: refSchema, - optional: true, - }, -}); + optional: true + } +}) testSchema.messageBox.messages({ minCount: 'blah', 'regEx email': '[label] is not a valid email address', - 'badUrl url': '[label] is not a valid URL', -}); + 'badUrl url': '[label] is not a valid URL' +}) -export default testSchema; +export default testSchema diff --git a/lib/testHelpers/validate.js b/lib/testHelpers/validate.js index 4c95803..99fe881 100644 --- a/lib/testHelpers/validate.js +++ b/lib/testHelpers/validate.js @@ -1,5 +1,5 @@ -export default function validate(ss, doc, options) { - const context = ss.newContext(); - context.validate(doc, options); - return context; +export default function validate (ss, doc, options) { + const context = ss.newContext() + context.validate(doc, options) + return context } diff --git a/lib/utility/appendAffectedKey.js b/lib/utility/appendAffectedKey.js index cc61e94..54be62e 100644 --- a/lib/utility/appendAffectedKey.js +++ b/lib/utility/appendAffectedKey.js @@ -1,4 +1,4 @@ -export default function appendAffectedKey(affectedKey, key) { - if (key === '$each') return affectedKey; - return affectedKey ? `${affectedKey}.${key}` : key; +export default function appendAffectedKey (affectedKey, key) { + if (key === '$each') return affectedKey + return affectedKey ? `${affectedKey}.${key}` : key } diff --git a/lib/utility/dateToDateString.js b/lib/utility/dateToDateString.js index c59d69a..cbcf5e9 100644 --- a/lib/utility/dateToDateString.js +++ b/lib/utility/dateToDateString.js @@ -1,10 +1,10 @@ /** * Given a Date instance, returns a date string of the format YYYY-MM-DD */ -export default function dateToDateString(date) { - let m = (date.getUTCMonth() + 1); - if (m < 10) m = `0${m}`; - let d = date.getUTCDate(); - if (d < 10) d = `0${d}`; - return `${date.getUTCFullYear()}-${m}-${d}`; +export default function dateToDateString (date) { + let m = (date.getUTCMonth() + 1) + if (m < 10) m = `0${m}` + let d = date.getUTCDate() + if (d < 10) d = `0${d}` + return `${date.getUTCFullYear()}-${m}-${d}` } diff --git a/lib/utility/forEachKeyAncestor.js b/lib/utility/forEachKeyAncestor.js index 580bc60..32a550f 100644 --- a/lib/utility/forEachKeyAncestor.js +++ b/lib/utility/forEachKeyAncestor.js @@ -2,17 +2,17 @@ * Run loopFunc for each ancestor key in a dot-delimited key. For example, * if key is "a.b.c", loopFunc will be called first with ('a.b', 'c') and then with ('a', 'b.c') */ -export default function forEachKeyAncestor(key, loopFunc) { - let lastDot; +export default function forEachKeyAncestor (key, loopFunc) { + let lastDot // Iterate the dot-syntax hierarchy - let ancestor = key; + let ancestor = key do { - lastDot = ancestor.lastIndexOf('.'); + lastDot = ancestor.lastIndexOf('.') if (lastDot !== -1) { - ancestor = ancestor.slice(0, lastDot); - const remainder = key.slice(ancestor.length + 1); - loopFunc(ancestor, remainder); // Remove last path component + ancestor = ancestor.slice(0, lastDot) + const remainder = key.slice(ancestor.length + 1) + loopFunc(ancestor, remainder) // Remove last path component } - } while (lastDot !== -1); + } while (lastDot !== -1) } diff --git a/lib/utility/getKeysWithValueInObj.js b/lib/utility/getKeysWithValueInObj.js index 5b4be0b..a399391 100644 --- a/lib/utility/getKeysWithValueInObj.js +++ b/lib/utility/getKeysWithValueInObj.js @@ -3,19 +3,19 @@ * other than null or undefined, and start with matchKey * plus a dot. */ -export default function getKeysWithValueInObj(obj, matchKey) { - const keysWithValue = []; +export default function getKeysWithValueInObj (obj, matchKey) { + const keysWithValue = [] - const keyAdjust = (k) => k.slice(0, matchKey.length + 1); - const matchKeyPlusDot = `${matchKey}.`; + const keyAdjust = (k) => k.slice(0, matchKey.length + 1) + const matchKeyPlusDot = `${matchKey}.` Object.keys(obj || {}).forEach((key) => { - const val = obj[key]; - if (val === undefined || val === null) return; + const val = obj[key] + if (val === undefined || val === null) return if (keyAdjust(key) === matchKeyPlusDot) { - keysWithValue.push(key); + keysWithValue.push(key) } - }); + }) - return keysWithValue; + return keysWithValue } diff --git a/lib/utility/getLastPartOfKey.js b/lib/utility/getLastPartOfKey.js index 1f8d46c..51b5f4d 100644 --- a/lib/utility/getLastPartOfKey.js +++ b/lib/utility/getLastPartOfKey.js @@ -5,12 +5,12 @@ * getLastPartOfKey('a.b.c', 'a') returns 'b.c' * getLastPartOfKey('a.b.$.c', 'a.b') returns 'c' */ -export default function getLastPartOfKey(key, ancestorKey) { - let lastPart = ''; - const startString = `${ancestorKey}.`; +export default function getLastPartOfKey (key, ancestorKey) { + let lastPart = '' + const startString = `${ancestorKey}.` if (key.indexOf(startString) === 0) { - lastPart = key.replace(startString, ''); - if (lastPart.startsWith('$.')) lastPart = lastPart.slice(2); + lastPart = key.replace(startString, '') + if (lastPart.startsWith('$.')) lastPart = lastPart.slice(2) } - return lastPart; + return lastPart } diff --git a/lib/utility/getLastPartOfKey.tests.js b/lib/utility/getLastPartOfKey.tests.js index beea181..60c88ad 100644 --- a/lib/utility/getLastPartOfKey.tests.js +++ b/lib/utility/getLastPartOfKey.tests.js @@ -1,14 +1,14 @@ /* eslint-disable func-names, prefer-arrow-callback */ -import { expect } from 'chai'; -import getLastPartOfKey from './getLastPartOfKey'; +import { expect } from 'chai' +import getLastPartOfKey from './getLastPartOfKey' describe('getLastPartOfKey', function () { it('returns the correct string for a non-array key', function () { - expect(getLastPartOfKey('a.b.c', 'a')).to.equal('b.c'); - }); + expect(getLastPartOfKey('a.b.c', 'a')).to.equal('b.c') + }) it('returns the correct string for an array key', function () { - expect(getLastPartOfKey('a.b.$.c', 'a.b')).to.equal('c'); - }); -}); + expect(getLastPartOfKey('a.b.$.c', 'a.b')).to.equal('c') + }) +}) diff --git a/lib/utility/getParentOfKey.js b/lib/utility/getParentOfKey.js index f5260df..c93c30a 100644 --- a/lib/utility/getParentOfKey.js +++ b/lib/utility/getParentOfKey.js @@ -3,7 +3,7 @@ * If no parent, returns an empty string. If withEndDot is true, the return * value will have a dot appended when it isn't an empty string. */ -export default function getParentOfKey(key, withEndDot) { - const lastDot = key.lastIndexOf('.'); - return lastDot === -1 ? '' : key.slice(0, lastDot + Number(!!withEndDot)); +export default function getParentOfKey (key, withEndDot) { + const lastDot = key.lastIndexOf('.') + return lastDot === -1 ? '' : key.slice(0, lastDot + Number(!!withEndDot)) } diff --git a/lib/utility/index.js b/lib/utility/index.js index 17ed6b0..ad9e629 100644 --- a/lib/utility/index.js +++ b/lib/utility/index.js @@ -1,10 +1,10 @@ -export { default as appendAffectedKey } from './appendAffectedKey'; -export { default as dateToDateString } from './dateToDateString'; -export { default as forEachKeyAncestor } from './forEachKeyAncestor'; -export { default as getKeysWithValueInObj } from './getKeysWithValueInObj'; -export { default as getLastPartOfKey } from './getLastPartOfKey'; -export { default as getParentOfKey } from './getParentOfKey'; -export { default as isEmptyObject } from './isEmptyObject'; -export { default as isObjectWeShouldTraverse } from './isObjectWeShouldTraverse'; -export { default as looksLikeModifier } from './looksLikeModifier'; -export { default as merge } from './merge'; +export { default as appendAffectedKey } from './appendAffectedKey' +export { default as dateToDateString } from './dateToDateString' +export { default as forEachKeyAncestor } from './forEachKeyAncestor' +export { default as getKeysWithValueInObj } from './getKeysWithValueInObj' +export { default as getLastPartOfKey } from './getLastPartOfKey' +export { default as getParentOfKey } from './getParentOfKey' +export { default as isEmptyObject } from './isEmptyObject' +export { default as isObjectWeShouldTraverse } from './isObjectWeShouldTraverse' +export { default as looksLikeModifier } from './looksLikeModifier' +export { default as merge } from './merge' diff --git a/lib/utility/isEmptyObject.js b/lib/utility/isEmptyObject.js index 69c3614..07d2e5e 100644 --- a/lib/utility/isEmptyObject.js +++ b/lib/utility/isEmptyObject.js @@ -3,14 +3,14 @@ * @param {Object} obj Object to test * @return {Boolean} True if it has no "own" properties */ -export default function isEmptyObject(obj) { +export default function isEmptyObject (obj) { /* eslint-disable no-restricted-syntax */ for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { - return false; + return false } } /* eslint-enable no-restricted-syntax */ - return true; + return true } diff --git a/lib/utility/isObjectWeShouldTraverse.js b/lib/utility/isObjectWeShouldTraverse.js index 0070717..bdc74c3 100644 --- a/lib/utility/isObjectWeShouldTraverse.js +++ b/lib/utility/isObjectWeShouldTraverse.js @@ -1,22 +1,22 @@ -export default function isObjectWeShouldTraverse(val) { +export default function isObjectWeShouldTraverse (val) { // Some of these types don't exist in old browsers so we'll catch and return false in those cases try { - if (val !== Object(val)) return false; + if (val !== Object(val)) return false // There are some object types that we know we shouldn't traverse because // they will often result in overflows and it makes no sense to validate them. - if (val instanceof Date) return false; - if (val instanceof Int8Array) return false; - if (val instanceof Uint8Array) return false; - if (val instanceof Uint8ClampedArray) return false; - if (val instanceof Int16Array) return false; - if (val instanceof Uint16Array) return false; - if (val instanceof Int32Array) return false; - if (val instanceof Uint32Array) return false; - if (val instanceof Float32Array) return false; - if (val instanceof Float64Array) return false; + if (val instanceof Date) return false + if (val instanceof Int8Array) return false + if (val instanceof Uint8Array) return false + if (val instanceof Uint8ClampedArray) return false + if (val instanceof Int16Array) return false + if (val instanceof Uint16Array) return false + if (val instanceof Int32Array) return false + if (val instanceof Uint32Array) return false + if (val instanceof Float32Array) return false + if (val instanceof Float64Array) return false } catch (e) { - return false; + return false } - return true; + return true } diff --git a/lib/utility/looksLikeModifier.js b/lib/utility/looksLikeModifier.js index ff2f463..5f1143e 100644 --- a/lib/utility/looksLikeModifier.js +++ b/lib/utility/looksLikeModifier.js @@ -1,6 +1,6 @@ /** * Returns true if any of the keys of obj start with a $ */ -export default function looksLikeModifier(obj) { - return !!Object.keys(obj || {}).find((key) => key.substring(0, 1) === '$'); +export default function looksLikeModifier (obj) { + return !!Object.keys(obj || {}).find((key) => key.substring(0, 1) === '$') } diff --git a/lib/utility/merge.js b/lib/utility/merge.js index d18d4d5..f6ff376 100644 --- a/lib/utility/merge.js +++ b/lib/utility/merge.js @@ -8,24 +8,24 @@ * pulling in a large dependency. */ -export default function merge(destination, ...sources) { +export default function merge (destination, ...sources) { sources.forEach((source) => { Object.keys(source).forEach((prop) => { - if (prop === '__proto__') return; // protect against prototype pollution + if (prop === '__proto__') return // protect against prototype pollution if ( - source[prop] - && source[prop].constructor - && source[prop].constructor === Object + source[prop] && + source[prop].constructor && + source[prop].constructor === Object ) { if (!destination[prop] || !destination[prop].constructor || destination[prop].constructor !== Object) { - destination[prop] = {}; + destination[prop] = {} } - merge(destination[prop], source[prop]); + merge(destination[prop], source[prop]) } else { - destination[prop] = source[prop]; + destination[prop] = source[prop] } - }); - }); + }) + }) - return destination; + return destination } diff --git a/lib/validation/allowedValuesValidator.js b/lib/validation/allowedValuesValidator.js index a30847a..6f7494e 100644 --- a/lib/validation/allowedValuesValidator.js +++ b/lib/validation/allowedValuesValidator.js @@ -1,18 +1,18 @@ -import { SimpleSchema } from '../SimpleSchema'; +import { SimpleSchema } from '../SimpleSchema' -export default function allowedValuesValidator() { - if (!this.valueShouldBeChecked) return; +export default function allowedValuesValidator () { + if (!this.valueShouldBeChecked) return - const { allowedValues } = this.definition; - if (!allowedValues) return; + const { allowedValues } = this.definition + if (!allowedValues) return - let isAllowed; + let isAllowed // set defined in scope and allowedValues is its instance if (typeof Set === 'function' && allowedValues instanceof Set) { - isAllowed = allowedValues.has(this.value); + isAllowed = allowedValues.has(this.value) } else { - isAllowed = allowedValues.includes(this.value); + isAllowed = allowedValues.includes(this.value) } - return isAllowed ? true : SimpleSchema.ErrorTypes.VALUE_NOT_ALLOWED; + return isAllowed ? true : SimpleSchema.ErrorTypes.VALUE_NOT_ALLOWED } diff --git a/lib/validation/requiredValidator.js b/lib/validation/requiredValidator.js index dae7691..04fdf34 100644 --- a/lib/validation/requiredValidator.js +++ b/lib/validation/requiredValidator.js @@ -1,5 +1,5 @@ -import { SimpleSchema } from '../SimpleSchema'; -import { getKeysWithValueInObj } from '../utility'; +import { SimpleSchema } from '../SimpleSchema' +import { getKeysWithValueInObj } from '../utility' // Check for missing required values. The general logic is this: // * If the operator is $unset or $rename, it's invalid. @@ -9,43 +9,43 @@ import { getKeysWithValueInObj } from '../utility'; // * We're validating a key of an object that is an array item. // * We're validating a document (as opposed to a modifier). // * We're validating a key under the $set operator in a modifier, and it's an upsert. -export default function requiredValidator() { +export default function requiredValidator () { const { - definition, isInArrayItemObject, isInSubObject, key, obj, operator, value, - } = this; - const { optional } = definition; + definition, isInArrayItemObject, isInSubObject, key, obj, operator, value + } = this + const { optional } = definition - if (optional) return; + if (optional) return // If value is null, no matter what, we add required - if (value === null) return SimpleSchema.ErrorTypes.REQUIRED; + if (value === null) return SimpleSchema.ErrorTypes.REQUIRED // If operator would remove, we add required - if (operator === '$unset' || operator === '$rename') return SimpleSchema.ErrorTypes.REQUIRED; + if (operator === '$unset' || operator === '$rename') return SimpleSchema.ErrorTypes.REQUIRED // The rest of these apply only if the value is undefined - if (value !== undefined) return; + if (value !== undefined) return // At this point, if it's a normal, non-modifier object, then a missing value is an error - if (!operator) return SimpleSchema.ErrorTypes.REQUIRED; + if (!operator) return SimpleSchema.ErrorTypes.REQUIRED // Everything beyond this point deals with modifier objects only // We can skip the required check for keys that are ancestors of those in $set or // $setOnInsert because they will be created by MongoDB while setting. - const keysWithValueInSet = getKeysWithValueInObj(obj.$set, key); - if (keysWithValueInSet.length) return; - const keysWithValueInSetOnInsert = getKeysWithValueInObj(obj.$setOnInsert, key); - if (keysWithValueInSetOnInsert.length) return; + const keysWithValueInSet = getKeysWithValueInObj(obj.$set, key) + if (keysWithValueInSet.length) return + const keysWithValueInSetOnInsert = getKeysWithValueInObj(obj.$setOnInsert, key) + if (keysWithValueInSetOnInsert.length) return // In the case of $set and $setOnInsert, the value may be undefined here // but it is set in another operator. So check that first. - const fieldInfo = this.field(key); - if (fieldInfo.isSet && fieldInfo.value !== null) return; + const fieldInfo = this.field(key) + if (fieldInfo.isSet && fieldInfo.value !== null) return // Required if in an array or sub object - if (isInArrayItemObject || isInSubObject) return SimpleSchema.ErrorTypes.REQUIRED; + if (isInArrayItemObject || isInSubObject) return SimpleSchema.ErrorTypes.REQUIRED // If we've got this far with an undefined $set or $setOnInsert value, it's a required error. - if (operator === '$set' || operator === '$setOnInsert') return SimpleSchema.ErrorTypes.REQUIRED; + if (operator === '$set' || operator === '$setOnInsert') return SimpleSchema.ErrorTypes.REQUIRED } diff --git a/lib/validation/typeValidator/doArrayChecks.js b/lib/validation/typeValidator/doArrayChecks.js index 2c8ae59..7b1e214 100644 --- a/lib/validation/typeValidator/doArrayChecks.js +++ b/lib/validation/typeValidator/doArrayChecks.js @@ -1,18 +1,18 @@ -import { SimpleSchema } from '../../SimpleSchema'; +import { SimpleSchema } from '../../SimpleSchema' -export default function doArrayChecks(def, keyValue) { +export default function doArrayChecks (def, keyValue) { // Is it an array? if (!Array.isArray(keyValue)) { - return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Array' }; + return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Array' } } // Are there fewer than the minimum number of items in the array? if (def.minCount !== null && keyValue.length < def.minCount) { - return { type: SimpleSchema.ErrorTypes.MIN_COUNT, minCount: def.minCount }; + return { type: SimpleSchema.ErrorTypes.MIN_COUNT, minCount: def.minCount } } // Are there more than the maximum number of items in the array? if (def.maxCount !== null && keyValue.length > def.maxCount) { - return { type: SimpleSchema.ErrorTypes.MAX_COUNT, maxCount: def.maxCount }; + return { type: SimpleSchema.ErrorTypes.MAX_COUNT, maxCount: def.maxCount } } } diff --git a/lib/validation/typeValidator/doDateChecks.js b/lib/validation/typeValidator/doDateChecks.js index 85157e4..a2069ad 100644 --- a/lib/validation/typeValidator/doDateChecks.js +++ b/lib/validation/typeValidator/doDateChecks.js @@ -1,17 +1,17 @@ -import { SimpleSchema } from '../../SimpleSchema'; -import { dateToDateString } from '../../utility'; +import { SimpleSchema } from '../../SimpleSchema' +import { dateToDateString } from '../../utility' -export default function doDateChecks(def, keyValue) { +export default function doDateChecks (def, keyValue) { // Is it an invalid date? - if (isNaN(keyValue.getTime())) return { type: SimpleSchema.ErrorTypes.BAD_DATE }; + if (isNaN(keyValue.getTime())) return { type: SimpleSchema.ErrorTypes.BAD_DATE } // Is it earlier than the minimum date? if (def.min && typeof def.min.getTime === 'function' && def.min.getTime() > keyValue.getTime()) { - return { type: SimpleSchema.ErrorTypes.MIN_DATE, min: dateToDateString(def.min) }; + return { type: SimpleSchema.ErrorTypes.MIN_DATE, min: dateToDateString(def.min) } } // Is it later than the maximum date? if (def.max && typeof def.max.getTime === 'function' && def.max.getTime() < keyValue.getTime()) { - return { type: SimpleSchema.ErrorTypes.MAX_DATE, max: dateToDateString(def.max) }; + return { type: SimpleSchema.ErrorTypes.MAX_DATE, max: dateToDateString(def.max) } } } diff --git a/lib/validation/typeValidator/doNumberChecks.js b/lib/validation/typeValidator/doNumberChecks.js index 75be6bc..a4b7a00 100644 --- a/lib/validation/typeValidator/doNumberChecks.js +++ b/lib/validation/typeValidator/doNumberChecks.js @@ -1,28 +1,28 @@ -import { SimpleSchema } from '../../SimpleSchema'; +import { SimpleSchema } from '../../SimpleSchema' // Polyfill to support IE11 -Number.isInteger = Number.isInteger || function isInteger(value) { - return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; -}; +Number.isInteger = Number.isInteger || function isInteger (value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value +} -export default function doNumberChecks(def, keyValue, op, expectsInteger) { +export default function doNumberChecks (def, keyValue, op, expectsInteger) { // Is it a valid number? if (typeof keyValue !== 'number' || isNaN(keyValue)) { - return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: expectsInteger ? 'Integer' : 'Number' }; + return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: expectsInteger ? 'Integer' : 'Number' } } // Assuming we are not incrementing, is the value less than the maximum value? if (op !== '$inc' && def.max !== null && (def.exclusiveMax ? def.max <= keyValue : def.max < keyValue)) { - return { type: def.exclusiveMax ? SimpleSchema.ErrorTypes.MAX_NUMBER_EXCLUSIVE : SimpleSchema.ErrorTypes.MAX_NUMBER, max: def.max }; + return { type: def.exclusiveMax ? SimpleSchema.ErrorTypes.MAX_NUMBER_EXCLUSIVE : SimpleSchema.ErrorTypes.MAX_NUMBER, max: def.max } } // Assuming we are not incrementing, is the value more than the minimum value? if (op !== '$inc' && def.min !== null && (def.exclusiveMin ? def.min >= keyValue : def.min > keyValue)) { - return { type: def.exclusiveMin ? SimpleSchema.ErrorTypes.MIN_NUMBER_EXCLUSIVE : SimpleSchema.ErrorTypes.MIN_NUMBER, min: def.min }; + return { type: def.exclusiveMin ? SimpleSchema.ErrorTypes.MIN_NUMBER_EXCLUSIVE : SimpleSchema.ErrorTypes.MIN_NUMBER, min: def.min } } // Is it an integer if we expect an integer? if (expectsInteger && !Number.isInteger(keyValue)) { - return { type: SimpleSchema.ErrorTypes.MUST_BE_INTEGER }; + return { type: SimpleSchema.ErrorTypes.MUST_BE_INTEGER } } } diff --git a/lib/validation/typeValidator/doStringChecks.js b/lib/validation/typeValidator/doStringChecks.js index 4ae57d6..8634aef 100644 --- a/lib/validation/typeValidator/doStringChecks.js +++ b/lib/validation/typeValidator/doStringChecks.js @@ -1,39 +1,39 @@ -import { SimpleSchema } from '../../SimpleSchema'; +import { SimpleSchema } from '../../SimpleSchema' -export default function doStringChecks(def, keyValue) { +export default function doStringChecks (def, keyValue) { // Is it a String? if (typeof keyValue !== 'string') { - return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'String' }; + return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'String' } } // Is the string too long? if (def.max !== null && def.max < keyValue.length) { - return { type: SimpleSchema.ErrorTypes.MAX_STRING, max: def.max }; + return { type: SimpleSchema.ErrorTypes.MAX_STRING, max: def.max } } // Is the string too short? if (def.min !== null && def.min > keyValue.length) { - return { type: SimpleSchema.ErrorTypes.MIN_STRING, min: def.min }; + return { type: SimpleSchema.ErrorTypes.MIN_STRING, min: def.min } } // Does the string match the regular expression? if ( - (def.skipRegExCheckForEmptyStrings !== true || keyValue !== '') - && def.regEx instanceof RegExp && !def.regEx.test(keyValue) + (def.skipRegExCheckForEmptyStrings !== true || keyValue !== '') && + def.regEx instanceof RegExp && !def.regEx.test(keyValue) ) { - return { type: SimpleSchema.ErrorTypes.FAILED_REGULAR_EXPRESSION, regExp: def.regEx.toString() }; + return { type: SimpleSchema.ErrorTypes.FAILED_REGULAR_EXPRESSION, regExp: def.regEx.toString() } } // If regEx is an array of regular expressions, does the string match all of them? if (Array.isArray(def.regEx)) { - let regExError; + let regExError def.regEx.every((re) => { if (!re.test(keyValue)) { - regExError = { type: SimpleSchema.ErrorTypes.FAILED_REGULAR_EXPRESSION, regExp: re.toString() }; - return false; + regExError = { type: SimpleSchema.ErrorTypes.FAILED_REGULAR_EXPRESSION, regExp: re.toString() } + return false } - return true; - }); - if (regExError) return regExError; + return true + }) + if (regExError) return regExError } } diff --git a/lib/validation/typeValidator/index.js b/lib/validation/typeValidator/index.js index c57dc18..7000053 100644 --- a/lib/validation/typeValidator/index.js +++ b/lib/validation/typeValidator/index.js @@ -1,52 +1,52 @@ -import { SimpleSchema } from '../../SimpleSchema'; -import doDateChecks from './doDateChecks'; -import doNumberChecks from './doNumberChecks'; -import doStringChecks from './doStringChecks'; -import doArrayChecks from './doArrayChecks'; +import { SimpleSchema } from '../../SimpleSchema' +import doDateChecks from './doDateChecks' +import doNumberChecks from './doNumberChecks' +import doStringChecks from './doStringChecks' +import doArrayChecks from './doArrayChecks' -export default function typeValidator() { - if (!this.valueShouldBeChecked) return; +export default function typeValidator () { + if (!this.valueShouldBeChecked) return - const def = this.definition; - const expectedType = def.type; - const keyValue = this.value; - const op = this.operator; + const def = this.definition + const expectedType = def.type + const keyValue = this.value + const op = this.operator - if (expectedType === String) return doStringChecks(def, keyValue); - if (expectedType === Number) return doNumberChecks(def, keyValue, op, false); - if (expectedType === SimpleSchema.Integer) return doNumberChecks(def, keyValue, op, true); + if (expectedType === String) return doStringChecks(def, keyValue) + if (expectedType === Number) return doNumberChecks(def, keyValue, op, false) + if (expectedType === SimpleSchema.Integer) return doNumberChecks(def, keyValue, op, true) if (expectedType === Boolean) { // Is it a boolean? - if (typeof keyValue === 'boolean') return; - return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Boolean' }; + if (typeof keyValue === 'boolean') return + return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Boolean' } } if (expectedType === Object || SimpleSchema.isSimpleSchema(expectedType)) { // Is it an object? if ( - keyValue === Object(keyValue) - && typeof keyValue[Symbol.iterator] !== 'function' - && !(keyValue instanceof Date) - ) return; - return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Object' }; + keyValue === Object(keyValue) && + typeof keyValue[Symbol.iterator] !== 'function' && + !(keyValue instanceof Date) + ) return + return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Object' } } - if (expectedType === Array) return doArrayChecks(def, keyValue); + if (expectedType === Array) return doArrayChecks(def, keyValue) if (expectedType instanceof Function) { // Generic constructor checks if (!(keyValue instanceof expectedType)) { // https://docs.mongodb.com/manual/reference/operator/update/currentDate/ - const dateTypeIsOkay = expectedType === Date - && op === '$currentDate' - && (keyValue === true || JSON.stringify(keyValue) === '{"$type":"date"}'); + const dateTypeIsOkay = expectedType === Date && + op === '$currentDate' && + (keyValue === true || JSON.stringify(keyValue) === '{"$type":"date"}') if (expectedType !== Date || !dateTypeIsOkay) { return { type: SimpleSchema.ErrorTypes.EXPECTED_TYPE, - dataType: expectedType.name, - }; + dataType: expectedType.name + } } } @@ -54,9 +54,9 @@ export default function typeValidator() { if (expectedType === Date) { // https://docs.mongodb.com/manual/reference/operator/update/currentDate/ if (op === '$currentDate') { - return doDateChecks(def, new Date()); + return doDateChecks(def, new Date()) } - return doDateChecks(def, keyValue); + return doDateChecks(def, keyValue) } } } diff --git a/package.js b/package.js index d8f2e45..f8d89af 100644 --- a/package.js +++ b/package.js @@ -4,25 +4,25 @@ Package.describe({ summary: 'A simple schema validation object with reactivity. Used by collection2 and autoform.', version: '2.0.0', git: 'https://github.com/aldeed/meteor-simple-schema.git' -}); +}) Npm.depends({ 'mongo-object': '3.0.1', 'message-box': '0.2.7', - 'clone': '2.1.2' -}); + clone: '2.1.2' +}) Package.onUse(function (api) { - api.versionsFrom(['2.3', '2.8.0', '3.0']); - api.use('ecmascript'); - api.mainModule('lib/main.js'); -}); + api.versionsFrom(['2.3', '2.8.0', '3.0']) + api.use('ecmascript') + api.mainModule('lib/main.js') +}) Package.onTest(function (api) { - api.versionsFrom(['2.3', '2.8.0', '3.0']); + api.versionsFrom(['2.3', '2.8.0', '3.0']) api.use([ - //'lmieulet:meteor-legacy-coverage@0.1.0', - //'lmieulet:meteor-coverage@4.0.0', + // 'lmieulet:meteor-legacy-coverage@0.1.0', + // 'lmieulet:meteor-coverage@4.0.0', 'meteortesting:mocha@2.0.0 || 3.2.0', 'ecmascript', 'tracker', @@ -62,5 +62,5 @@ Package.onTest(function (api) { 'lib/SimpleSchema_rules.tests.js', 'lib/SimpleSchema_type.tests.js', 'lib/reactivity.tests.js' - ]); -}); + ]) +})