Skip to content

Commit

Permalink
rebuild
Browse files Browse the repository at this point in the history
  • Loading branch information
jquense committed Mar 29, 2016
1 parent 9dbeb6b commit afe783f
Show file tree
Hide file tree
Showing 12 changed files with 224 additions and 107 deletions.
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ json separate from validating it, via the `cast` method.
- [`.reach(Schema schema, String path, Object options)`](#reachschema-schema-string-path-object-options)
- [`.addMethod(schemaType, name, method)`](#addmethodschematype-name-method)
- [`ValidationError(String|Array<String> errors, Any value, String path)`](#validationerrorstringarraystring-errors-any-value-string-path)
- [`ref(String path, Object options)`](#refstring-path-object-options)
- [mixed](#mixed)
- [`mixed.clone()`](#mixedclone)
- [`mixed.label(String label)`](#mixedlabelstring-label)
Expand All @@ -39,36 +40,36 @@ json separate from validating it, via the `cast` method.
- [`mixed.typeError(String message)`](#mixedtypeerrorstring-message)
- [`mixed.oneOf(Array<Any> arrayOfValues, [String message])` Alias: `equals`](#mixedoneofarrayany-arrayofvalues-string-message-alias-equals)
- [`mixed.notOneOf(Array<Any> arrayOfValues, [String message])`](#mixednotoneofarrayany-arrayofvalues-string-message)
- [`mixed.when(String key, Object options | Function func)`](#mixedwhenstring-key-object-options--function-func)
- [`mixed.when(String|Array<String> keys, Object options | Function func)`](#mixedwhenstringarraystring-keys-object-options--function-func)
- [`mixed.test(String name, String message, Function fn, [Bool callbackStyleAsync])`](#mixedteststring-name-string-message-function-fn-bool-callbackstyleasync)
- [`mixed.test(Object options)`](#mixedtestobject-options)
- [`mixed.transform(Function fn)`](#mixedtransformfunction-fn)
- [string](#string)
- [`string.required([String message])`](#stringrequiredstring-message)
- [`string.min(Number limit, [String message])`](#stringminnumber-limit-string-message)
- [`string.max(Number limit, [String message])`](#stringmaxnumber-limit-string-message)
- [`string.min(Number|Ref limit, [String message])`](#stringminnumberref-limit-string-message)
- [`string.max(Number|Ref limit, [String message])`](#stringmaxnumberref-limit-string-message)
- [`string.matches(Regex regex, [String message])`](#stringmatchesregex-regex-string-message)
- [`string.email([String message])`](#stringemailstring-message)
- [`string.url([String message])`](#stringurlstring-message)
- [`string.trim([String message])`](#stringtrimstring-message)
- [`string.lowercase([String message])`](#stringlowercasestring-message)
- [`string.uppercase([String message])`](#stringuppercasestring-message)
- [number](#number)
- [`number.min(Number limit, [String message])`](#numberminnumber-limit-string-message)
- [`number.max(Number limit, [String message])`](#numbermaxnumber-limit-string-message)
- [`number.min(Number|Ref limit, [String message])`](#numberminnumberref-limit-string-message)
- [`number.max(Number|Ref limit, [String message])`](#numbermaxnumberref-limit-string-message)
- [`number.positive([String message])`](#numberpositivestring-message)
- [`number.negative([String message])`](#numbernegativestring-message)
- [`number.integer([String message])`](#numberintegerstring-message)
- [`round(String type)` - 'floor', 'ceil', 'round'](#roundstring-type---floor-ceil-round)
- [boolean](#boolean)
- [date](#date)
- [`date.min(Date|String limit, [String message])`](#datemindatestring-limit-string-message)
- [`date.max(Date|String limit, [String message])`](#datemaxdatestring-limit-string-message)
- [`date.min(Date|String|Ref limit, [String message])`](#datemindatestringref-limit-string-message)
- [`date.max(Date|String|Ref limit, [String message])`](#datemaxdatestringref-limit-string-message)
- [array](#array)
- [`array.of(Schema type)`](#arrayofschema-type)
- [`array.required([String message])`](#arrayrequiredstring-message)
- [`array.min(Number limit, [String message])`](#arrayminnumber-limit-string-message)
- [`array.max(Number limit, [String message])`](#arraymaxnumber-limit-string-message)
- [`array.min(Number|Ref limit, [String message])`](#arrayminnumberref-limit-string-message)
- [`array.max(Number|Ref limit, [String message])`](#arraymaxnumberref-limit-string-message)
- [`array.compact(Function rejector)`](#arraycompactfunction-rejector)
- [object](#object)
- [`object.shape(Object schemaHash, [noSortEdges])`](#objectshapeobject-schemahash-nosortedges)
Expand Down
4 changes: 2 additions & 2 deletions lib/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ inherits(ArraySchema, MixedSchema, {
exclusive: true,
params: { min: _min },
test: function test(value) {
return isAbsent(value) || value.length >= _min;
return isAbsent(value) || value.length >= this.resolve(_min);
}
});
},
Expand All @@ -141,7 +141,7 @@ inherits(ArraySchema, MixedSchema, {
exclusive: true,
params: { max: _max },
test: function test(value) {
return isAbsent(value) || value.length <= _max;
return isAbsent(value) || value.length <= this.resolve(_max);
}
});
},
Expand Down
4 changes: 2 additions & 2 deletions lib/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ inherits(DateSchema, MixedSchema, {
message: msg || locale.min,
params: { min: _min },
test: function test(value) {
return isAbsent(value) || value >= limit;
return isAbsent(value) || value >= this.resolve(limit);
}
});
},
Expand All @@ -63,7 +63,7 @@ inherits(DateSchema, MixedSchema, {
message: msg || locale.max,
params: { max: _max },
test: function test(value) {
return isAbsent(value) || value <= limit;
return isAbsent(value) || value <= this.resolve(limit);
}
});
}
Expand Down
6 changes: 5 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';
var mixed = require('./mixed'),
bool = require('./boolean');
bool = require('./boolean'),
Ref = require('./util/reference');

var isSchema = function isSchema(schema) {
return schema && !!schema.__isYupSchema__;
Expand All @@ -19,6 +20,9 @@ module.exports = {
reach: require('./util/reach'),

ValidationError: require('./util/validation-error'),
ref: function ref(key, options) {
return new Ref(key, options);
},

isSchema: isSchema,

Expand Down
45 changes: 32 additions & 13 deletions lib/mixed.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

var Promise = require('promise/lib/es6-extensions'),
Condition = require('./util/condition'),
ValidationError = require('./util/validation-error'),
locale = require('./locale.js').mixed,
_ = require('./util/_'),
isAbsent = require('./util/isAbsent'),
cloneDeep = require('./util/clone'),
createValidation = require('./util/createValidation'),
BadSet = require('./util/set');
BadSet = require('./util/set'),
Ref = require('./util/reference');

var notEmpty = function notEmpty(value) {
return !isAbsent(value);
Expand All @@ -28,6 +28,7 @@ function SchemaType() {
if (!(this instanceof SchemaType)) return new SchemaType();

this._deps = [];
this._conditions = [];
this._options = { abortEarly: true, recursive: true };
this._exclusive = Object.create(null);
this._whitelist = new BadSet();
Expand Down Expand Up @@ -98,9 +99,11 @@ SchemaType.prototype = {
return !this._typeCheck || this._typeCheck(v);
},

cast: function cast(_value, _opts) {
var schema = this._resolve((_opts || {}).context);
return schema._cast(_value, _opts);
cast: function cast(value) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

var schema = this._resolve(opts.context, opts.parent);
return schema._cast(value, opts);
},

_cast: function _cast(_value) {
Expand All @@ -116,8 +119,8 @@ SchemaType.prototype = {
},

_resolve: function _resolve(context, parent) {
if (this._deps.length) {
return this._deps.reduce(function (schema, match) {
if (this._conditions.length) {
return this._conditions.reduce(function (schema, match) {
return match.resolve(schema, match.getValue(parent, context));
}, this);
}
Expand Down Expand Up @@ -262,11 +265,17 @@ SchemaType.prototype = {
return next;
},

when: function when(key, options) {
when: function when(keys, options) {
var next = this.clone(),
dep = new Condition(key, next._type, options);
deps = [].concat(keys).map(function (key) {
return new Ref(key);
});

deps.forEach(function (dep) {
if (!dep.isContext) next._deps.push(dep.key);
});

next._deps.push(dep);
next._conditions.push(new Condition(deps, options));

return next;
},
Expand All @@ -279,7 +288,9 @@ SchemaType.prototype = {
name: 'typeError',
test: function test(value) {
if (value !== undefined && !this.schema.isType(value)) return this.createError({
params: { type: this.schema._type }
params: {
type: this.schema._type
}
});
return true;
}
Expand All @@ -304,7 +315,11 @@ SchemaType.prototype = {
name: 'oneOf',
test: function test(value) {
var valids = this.schema._whitelist;
if (valids.length && !(valids.has(value) || isAbsent(value))) return this.createError({ params: { values: valids.values().join(', ') } });
if (valids.length && !(value === undefined || valids.has(value))) return this.createError({
params: {
values: valids.values().join(', ')
}
});
return true;
}
});
Expand All @@ -327,7 +342,11 @@ SchemaType.prototype = {
name: 'notOneOf',
test: function test(value) {
var invalids = this.schema._blacklist;
if (invalids.length && invalids.has(value)) return this.createError({ params: { values: invalids.values().join(', ') } });
if (invalids.length && invalids.has(value)) return this.createError({
params: {
values: invalids.values().join(', ')
}
});
return true;
}
});
Expand Down
4 changes: 2 additions & 2 deletions lib/number.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ inherits(NumberSchema, SchemaObject, {
params: { min: _min },
message: msg || locale.min,
test: function test(value) {
return isAbsent(value) || value >= _min;
return isAbsent(value) || value >= this.resolve(_min);
}
});
},
Expand All @@ -59,7 +59,7 @@ inherits(NumberSchema, SchemaObject, {
params: { max: _max },
message: msg || locale.max,
test: function test(value) {
return isAbsent(value) || value <= _max;
return isAbsent(value) || value <= this.resolve(_max);
}
});
},
Expand Down
48 changes: 33 additions & 15 deletions lib/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var Promise = require('promise/lib/es6-extensions');
var toposort = require('toposort');
var locale = require('./locale.js').object;
var split = require('property-expr').split;
var Ref = require('./util/reference');
var c = require('case');

var _require = require('./util/_');
Expand All @@ -16,6 +17,7 @@ var transform = _require.transform;
var assign = _require.assign;
var inherits = _require.inherits;
var collectErrors = _require.collectErrors;
var isSchema = _require.isSchema;
var has = _require.has;

var isRecursive = function isRecursive(schema) {
Expand All @@ -30,7 +32,9 @@ c.type('altCamel', function (str) {
});

var childSchema = function childSchema(field, parent) {
return isRecursive(field) ? field.of ? field.of(parent) : parent : field;
if (!isRecursive(field)) return field;

return field.of ? field.of(parent) : parent;
};

var scopeError = function scopeError(value) {
Expand Down Expand Up @@ -85,7 +89,9 @@ inherits(ObjectSchema, MixedSchema, {
return isObject(value) || typeof value === 'function';
},

_cast: function _cast(_value, _opts) {
_cast: function _cast(_value) {
var _opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

var schema = this,
value = MixedSchema.prototype._cast.call(schema, _value);

Expand All @@ -100,23 +106,33 @@ inherits(ObjectSchema, MixedSchema, {
props = schema._nodes.concat(extra);

schema.withMutation(function () {
var innerOptions = _extends({}, _opts, { context: {} });
var innerOptions = _extends({}, _opts, { parent: {} });

value = transform(props, function (obj, prop) {
var field = fields[prop];
var exists = has(value, prop);

if (exists && fields[prop]) {
var fieldSchema = childSchema(fields[prop], schema['default'](undefined));
if (Ref.isRef(field)) {
var refValue = field.getValue(obj, innerOptions.context);

if (refValue !== undefined) obj[prop] = refValue;
} else if (exists && field) {
// ugly optimization avoiding a clone. clears default for recursive
// cast and resets it below;
var hasDflt = has(schema, '_default'),
dflt = schema._default;

var fieldSchema = childSchema(field, schema['default'](undefined));

obj[prop] = fieldSchema.cast(value[prop], innerOptions);
} else if (exists && !strip) obj[prop] = value[prop];else if (fields[prop]) {
var fieldDefault = fields[prop]['default'] ? fields[prop]['default']() : undefined;

if (hasDflt) schema['default'](dflt);else delete schema._default;
} else if (exists && !strip) obj[prop] = value[prop];else if (field) {
var fieldDefault = field['default'] ? field['default']() : undefined;

if (fieldDefault !== undefined) obj[prop] = fieldDefault;
}
}, innerOptions.context);

delete schema._default;
}, innerOptions.parent);
});

return value;
Expand Down Expand Up @@ -257,18 +273,20 @@ function sortFields(fields) {
nodes = [];

for (var key in fields) if (has(fields, key)) {
var value = fields[key];

if (! ~nodes.indexOf(key)) nodes.push(key);

fields[key]._deps && fields[key]._deps.forEach(function (dep) {
var addNode = function addNode(depPath) {
//eslint-disable-line no-loop-func
if (dep.isContext) return;

var node = split(dep.key)[0];
var node = split(depPath)[0];

if (! ~nodes.indexOf(node)) nodes.push(node);

if (! ~excludes.indexOf(key + '-' + node)) edges.push([key, node]);
});
};

if (Ref.isRef(value) && !value.isContext) addNode(value.path);else if (isSchema(value)) value._deps.forEach(addNode);
}

return toposort.array(nodes, edges).reverse();
Expand Down
4 changes: 2 additions & 2 deletions lib/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ inherits(StringSchema, MixedSchema, {
message: msg || locale.min,
params: { min: _min },
test: function test(value) {
return isAbsent(value) || value.length >= _min;
return isAbsent(value) || value.length >= this.resolve(_min);
}
});
},
Expand All @@ -66,7 +66,7 @@ inherits(StringSchema, MixedSchema, {
message: msg || locale.max,
params: { max: _max },
test: function test(value) {
return isAbsent(value) || value.length <= _max;
return isAbsent(value) || value.length <= this.resolve(_max);
}
});
},
Expand Down
Loading

0 comments on commit afe783f

Please sign in to comment.