Skip to content

string type arrays handling dates #84

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}
`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this call to ajv needed? I would refrain from doing so. Callling ajv is costly.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mcollina I'm not sure really. All I have done is to check if the data is a Date when the type is string. the ajv stuff was there before already.

`
}
laterCode = nestedResult.laterCode
})
code += `
else json+= null
`
} else {
throw new Error(`${type} unsupported`)
}
Expand Down
19 changes: 19 additions & 0 deletions test/typesArray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
})