fast-json-stringify icon indicating copy to clipboard operation
fast-json-stringify copied to clipboard

Object should pass validation after it is modified by if-then-else logic.

Open TommyDew42 opened this issue 3 years ago • 2 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the bug has not already been reported

Fastify version

Plugin version

5.4.0

Node.js version

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

Description

From a PR comment. Object should pass validation after it is modified by if-then-else logic. It seems that it's because the anyof validator.validate receive { a:[] } instead of the object after modified with const value.

Steps to Reproduce

test('anyOf with string and array', (t) => {
  t.plan(2)

  const schema = {
    anyOf: [
      { type: 'string' },
      {
        type: 'object',
        properties: {
          a: {
            type: 'array',
            if: { items: { type: 'number' }, minItems: 1 },
            then: { items: { type: 'number' } },
            else: { const: ['const item'] }
          }
        }
      }
    ]
  }

  const stringify = build(schema)

  t.equal(stringify('foo'), '"foo"') // ok
  t.equal(stringify({ a: [1, 2, 3] }), JSON.stringify({ a: [1, 2, 3] })) // ok
  t.equal(
    stringify({ a: [] }),
    JSON.stringify({ a: ['const item'] })
  ) // throw error: The value {"a":[]} does not match schema definition.
})

Expected Behavior

  t.equal(
    stringify({ a: [] }),
    JSON.stringify({ a: ['const item'] })
  ) // this should pass and no schema error is thrown

TommyDew42 avatar Oct 07 '22 15:10 TommyDew42

We have a discussion, where we are trying to resolve cases like that. It's not done yet, but from what I see now, I think it's a correct behavior. You can join of you want.

https://github.com/fastify/fast-json-stringify/discussions/532#discussioncomment-3799614

ivan-tymoshenko avatar Oct 08 '22 12:10 ivan-tymoshenko

But your case will not work anyway, because you have an array under anyOf, which mean that fjs uses Ajv for validation. And you pass an invalid data.

ivan-tymoshenko avatar Oct 08 '22 13:10 ivan-tymoshenko