Skip to content

Commit

Permalink
[fixed] pass options to array sub schema
Browse files Browse the repository at this point in the history
fixes #21
  • Loading branch information
jquense committed Feb 1, 2016
1 parent 463efbc commit 335eb18
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
17 changes: 11 additions & 6 deletions src/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ let hasLength = value => !isAbsent(value) && value.length > 0;
module.exports = ArraySchema

function ArraySchema(){
if ( !(this instanceof ArraySchema))
if (!(this instanceof ArraySchema))
return new ArraySchema()

MixedSchema.call(this, { type: 'array'})
Expand All @@ -27,11 +27,6 @@ function ArraySchema(){
values = JSON.parse(values)
} catch (err){ values = null }

if (Array.isArray(values))
return this._subType
? values.map(this._subType.cast, this._subType)
: values

return this.isType(values) ? values : null
})
})
Expand All @@ -43,6 +38,16 @@ inherits(ArraySchema, MixedSchema, {
return Array.isArray(v)
},

_cast(_value, _opts) {
var value = MixedSchema.prototype._cast.call(this, _value)

//should ignore nulls here
if (!this._typeCheck(value) || !this._subType)
return value;

return value.map(v => this._subType.cast(v, _opts))
},

_validate(_value, _opts, _state){
var errors = []
, context, subType, schema, endEarly, recursive;
Expand Down
15 changes: 14 additions & 1 deletion test/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe('Array types', function(){
it('should CAST correctly', function(){
var inst = array();

inst.cast('[2,3,5,6]').should.eql([2,3,5,6])
inst.cast('[2,3,5,6]').should.eql([2, 3, 5, 6])

inst.cast(['4', 5, false]).should.eql(['4', 5, false])

Expand Down Expand Up @@ -53,6 +53,19 @@ describe('Array types', function(){
inst.nullable().isType(null).should.equal(true)
})

it('should cast children', function(){
array()
.of(number())
.cast(['1', '3']).should.eql([1, 3])
})

it('should pass options to children', function(){
array()
.of(object({ name: string() }))
.cast([{ id: 1, name: 'john' }], { stripUnknown: true })
.should.eql([{name: 'john'}])
})

it('should VALIDATE correctly', function(){

var inst = array().required().of(number().max(5))
Expand Down

0 comments on commit 335eb18

Please sign in to comment.