diff --git a/index.js b/index.js index 422852d8..709a2e7b 100644 --- a/index.js +++ b/index.js @@ -670,12 +670,22 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe type.forEach((type, index) => { var tempSchema = {type: type} var nestedResult = nested(laterCode, name, key, tempSchema, externalSchema, fullSchema, subKey) - code += ` - ${index === 0 ? 'if' : 'else if'}(ajv.validate(${require('util').inspect(tempSchema, {depth: null})}, obj${accessor})) + if (type === 'string') { + code += ` + ${index === 0 ? 'if' : 'else if'}(obj${accessor} instanceof Date || ajv.validate(${require('util').inspect(tempSchema, {depth: null})}, obj${accessor})) + ${nestedResult.code} + ` + } else { + code += ` + ${index === 0 ? 'if' : 'else if'}(ajv.validate(${require('util').inspect(tempSchema, {depth: null})}, obj${accessor})) ${nestedResult.code} - ` + ` + } laterCode = nestedResult.laterCode }) + code += ` + else json+= null + ` } else { throw new Error(`${type} unsupported`) } diff --git a/test/typesArray.test.js b/test/typesArray.test.js index d1baa272..77e97d38 100644 --- a/test/typesArray.test.js +++ b/test/typesArray.test.js @@ -182,3 +182,22 @@ test('object with anyOf and multiple types', (t) => { t.fail() } }) + +test('string type array can handle dates', (t) => { + t.plan(1) + const schema = { + type: 'object', + properties: { + date: { type: ['string'] } + } + } + const stringify = build(schema) + try { + const value = stringify({ + date: new Date('2018-04-20T07:52:31.017Z') + }) + t.is(value, '{"date":"2018-04-20T07:52:31.017Z"}') + } catch (e) { + t.fail() + } +})