fastify/fast-json-stringify

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

TommyDew42 opened this issue · 2 comments

Prerequisites

  • I have written a descriptive issue title
  • 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

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.

#532 (reply in thread)

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.