Skip to content

Commit 335eb18

Browse files
committed
[fixed] pass options to array sub schema
fixes #21
1 parent 463efbc commit 335eb18

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

src/array.js

+11-6
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ let hasLength = value => !isAbsent(value) && value.length > 0;
1515
module.exports = ArraySchema
1616

1717
function ArraySchema(){
18-
if ( !(this instanceof ArraySchema))
18+
if (!(this instanceof ArraySchema))
1919
return new ArraySchema()
2020

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

30-
if (Array.isArray(values))
31-
return this._subType
32-
? values.map(this._subType.cast, this._subType)
33-
: values
34-
3530
return this.isType(values) ? values : null
3631
})
3732
})
@@ -43,6 +38,16 @@ inherits(ArraySchema, MixedSchema, {
4338
return Array.isArray(v)
4439
},
4540

41+
_cast(_value, _opts) {
42+
var value = MixedSchema.prototype._cast.call(this, _value)
43+
44+
//should ignore nulls here
45+
if (!this._typeCheck(value) || !this._subType)
46+
return value;
47+
48+
return value.map(v => this._subType.cast(v, _opts))
49+
},
50+
4651
_validate(_value, _opts, _state){
4752
var errors = []
4853
, context, subType, schema, endEarly, recursive;

test/array.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ describe('Array types', function(){
1616
it('should CAST correctly', function(){
1717
var inst = array();
1818

19-
inst.cast('[2,3,5,6]').should.eql([2,3,5,6])
19+
inst.cast('[2,3,5,6]').should.eql([2, 3, 5, 6])
2020

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

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

56+
it('should cast children', function(){
57+
array()
58+
.of(number())
59+
.cast(['1', '3']).should.eql([1, 3])
60+
})
61+
62+
it('should pass options to children', function(){
63+
array()
64+
.of(object({ name: string() }))
65+
.cast([{ id: 1, name: 'john' }], { stripUnknown: true })
66+
.should.eql([{name: 'john'}])
67+
})
68+
5669
it('should VALIDATE correctly', function(){
5770

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

0 commit comments

Comments
 (0)