Skip to content

fix: remove array items type checking #524

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
Sep 6, 2022
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
52 changes: 5 additions & 47 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -641,19 +641,14 @@ function buildArray (location) {

if (Array.isArray(itemsSchema)) {
for (let i = 0; i < itemsSchema.length; i++) {
const item = itemsSchema[i]
const tmpRes = buildValue(mergeLocation(itemsLocation, i), `obj[${i}]`)
functionCode += `
if (${i} < arrayLength) {
if (${buildArrayTypeCondition(item.type, `[${i}]`)}) {
let json = ''
${tmpRes}
jsonOutput += json
if (${i} < arrayLength - 1) {
jsonOutput += ','
}
} else {
throw new Error(\`Item at ${i} does not match schema definition.\`)
let json = ''
${tmpRes}
jsonOutput += json
if (${i} < arrayLength - 1) {
jsonOutput += ','
}
}
`
Expand Down Expand Up @@ -690,43 +685,6 @@ function buildArray (location) {
return functionName
}

function buildArrayTypeCondition (type, accessor) {
let condition
switch (type) {
case 'null':
condition = `obj${accessor} === null`
break
case 'string':
condition = `typeof obj${accessor} === 'string'`
break
case 'integer':
condition = `Number.isInteger(obj${accessor})`
break
case 'number':
condition = `Number.isFinite(obj${accessor})`
break
case 'boolean':
condition = `typeof obj${accessor} === 'boolean'`
break
case 'object':
condition = `obj${accessor} && typeof obj${accessor} === 'object' && obj${accessor}.constructor === Object`
break
case 'array':
condition = `Array.isArray(obj${accessor})`
break
default:
if (Array.isArray(type)) {
const conditions = type.map((subType) => {
return buildArrayTypeCondition(subType, accessor)
})
condition = `(${conditions.join(' || ')})`
} else {
throw new Error(`${type} unsupported`)
}
}
return condition
}

let genFuncNameCounter = 0
function generateFuncName () {
return 'anonymous' + genFuncNameCounter++
Expand Down
65 changes: 47 additions & 18 deletions test/array.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const test = require('tap').test
const { DateTime } = require('luxon')
const validator = require('is-my-json-valid')
const build = require('..')

Expand Down Expand Up @@ -152,28 +153,56 @@ buildTest({
'@data': ['test']
})

test('invalid items throw', (t) => {
test('coerce number to string type item', (t) => {
Copy link
Member

Choose a reason for hiding this comment

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

Is patternProperties still a thing?

Copy link
Member Author

Choose a reason for hiding this comment

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

I don't know why there is a patternProperties in this test. It works without them ('invalid' string always doesn't match the object schema). The test will work differently after this PR, but not because of patternProperties.

How the test works now:

test('invalid items throw', (t) => {
  t.plan(1)
  const schema = {
    type: 'object',
    properties: {
      args: {
        type: 'array',
        items: [
          {
            type: 'object',
            patternProperties: {
              '.*': {
                type: 'string'
              }
            }
          }
        ]
      }
    }
  }
  const stringify = build(schema)
  t.throws(() => stringify({ args: ['invalid'] })) // throws an error because 'invalid' is not an object
})

How it will work:

test('invalid items throw', (t) => {
  t.plan(1)
  const schema = {
    type: 'object',
    properties: {
      args: {
        type: 'array',
        items: [
          {
            type: 'object',
            patternProperties: {
              '.*': {
                type: 'string'
              }
            }
          }
        ]
      }
    }
  }
  const stringify = build(schema)
  t.equal(stringify({ args: ['invalid'] }), '{"args":[{"0":"i","1":"n","2":"v","3":"a","4":"l","5":"i","6":"d"}]}') // it coerces 'invalid' string to the object schema
})

It will work just like the same schema with patternProperties works now without array.

test('invalid items throw', (t) => {
  t.plan(1)
  const schema = {
    type: 'object',
    patternProperties: {
      '.*': {
        type: 'string'
      }
    }
  }
  const stringify = build(schema)
  t.equal(stringify('invalid'), '{"0":"i","1":"n","2":"v","3":"a","4":"l","5":"i","6":"d"}')
})

Copy link
Member Author

Choose a reason for hiding this comment

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

@Eomm I decided to remove the test instead of updating it because this coercion looks like nonsense. If you want I can add the test like that.

Copy link
Member

Choose a reason for hiding this comment

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

I like the idea of removing all the "validation" logic here, but I would move it to the next branch.

I think the new output could warn a user that does not understand what is going on: I would prefer an empty output instead of {"0":"i","1":"n","2":"v","3":"a","4":"l","5":"i","6":"d"}, but we can't do it without keeping the "validation" logic tho

Copy link
Member Author

Choose a reason for hiding this comment

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

The output you see isn't related to the array at all. It's all about how FJS coerces string to object.

t.plan(1)
const schema = {
type: 'object',
properties: {
args: {
type: 'array',
items: [
{
type: 'object',
patternProperties: {
'.*': {
type: 'string'
}
}
}
]
}
}
type: 'array',
items: [{ type: 'string' }]
}
const stringify = build(schema)
t.equal(stringify([1]), '["1"]')
})

test('coerce string to number type item', (t) => {
t.plan(1)
const schema = {
type: 'array',
items: [{ type: 'number' }]
}
const stringify = build(schema)
t.equal(stringify(['1']), '[1]')
})

test('coerce string to integer type item', (t) => {
t.plan(1)
const schema = {
type: 'array',
items: [{ type: 'integer' }]
}
const stringify = build(schema)
t.equal(stringify(['1']), '[1]')
})

test('coerce date to string (date) type item', (t) => {
t.plan(1)
const schema = {
type: 'array',
items: [{ type: 'string', format: 'date' }]
}
const stringify = build(schema)
const date = new Date()
t.equal(stringify([date]), `["${DateTime.fromJSDate(date).toISODate()}"]`)
})

test('coerce date to string (time) type item', (t) => {
t.plan(1)
const schema = {
type: 'array',
items: [{ type: 'string', format: 'time' }]
}
const stringify = build(schema)
t.throws(() => stringify({ args: ['invalid'] }))
const date = new Date()
t.equal(stringify([date]), `["${DateTime.fromJSDate(date).toFormat('HH:mm:ss')}"]`)
})

buildTest({
Expand Down