fastify/fast-json-stringify

Schema serialization of anyOf/oneOf properties are parsed incorrectly

royhamulak opened this issue · 1 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

4.22.0

Plugin version

No response

Node.js version

18.x

Operating system

macOS

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

not relevant

Description

PR#630 introduced new serialization for anyOf or oneOf in object schemas.
When these are defined on an object schema, the parsed value leaves a trailing comma which breaks the JSON standard.

Steps to Reproduce

import fastJson from 'fast-json-stringify'

// A schema that defines that `prop1` is mandatory and either `prop2` or `prop3` must be provided
// but both of these props can be provided as well
const schema = {
  type: 'object',
  properties: {
    prop1: {type: 'string'},
    prop2: {type: 'string'},
    prop3: {type: 'string'},
  },
  required: ['prop1'],
  anyOf: [{required: ['prop2']}, {required: ['prop3']}],
}

const stringify = fastJson(schema)

console.log(stringify({prop1: 'test', prop2: 'test2'})) // output: {"prop1":"test","prop2":"test2",}
console.log(stringify({prop1: 'test', prop3: 'test3'})) // output: {"prop1":"test","prop3":"test3",}
console.log(stringify({prop1: 'test', prop2: 'test2', prop3: 'test3'})) // output: {"prop1":"test","prop2":"test2","prop3":"test3",}

it's the same for oneOf instead of anyOf

Expected Behavior

return a proper stringified version of the object provided without the trailing comma.

Thanks for reporting! Would you like to send a Pull Request to address this issue? Remember to add unit tests.