fastify / fastify/fast-json-stringify

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

Open
#550 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
3.7k
Forks
226
Avg merge
1d 59m
Merged PRs (30d)
3

Description

### 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](https://github.com/fastify/fast-json-stringify/pull/545#issuecomment-1261195251). 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

```js
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

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.