Skip to content
Open
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
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,10 @@ function buildMultiTypeSerializer (context, location, input) {
`
break
case 'string': {
// An array has its own `toString`, so it would otherwise be captured by
// the duck-typing check below and serialized as a comma-joined string
// (dropping the JSON structure). Exclude arrays here so a sibling
// `array` type in the same `type` list can match.
code += `
${statement}(
typeof ${input} === "string" ||
Expand All @@ -927,6 +931,7 @@ function buildMultiTypeSerializer (context, location, input) {
${input} instanceof RegExp ||
(
typeof ${input} === "object" &&
!Array.isArray(${input}) &&
typeof ${input}.toString === "function" &&
${input}.toString !== Object.prototype.toString
)
Expand Down
33 changes: 33 additions & 0 deletions test/typesArray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -607,3 +607,36 @@ test('multi-type [object, array] round-trips an array of objects (JSON:API data)
}
t.assert.deepEqual(JSON.parse(stringify(objectInput)), objectInput)
})

test('multi-type [string, array] round-trips an array', (t) => {
t.plan(2)

const schema = {
type: 'object',
properties: {
data: {
type: ['string', 'array'],
items: {
type: 'object',
properties: {
id: { type: 'string' },
type: { type: 'string' }
}
}
}
}
}

const stringify = build(schema, { ajv: { allowUnionTypes: true } })

const arrayInput = {
data: [
{ id: '1', type: 'article' },
{ id: '2', type: 'article' }
]
}
t.assert.deepEqual(JSON.parse(stringify(arrayInput)), arrayInput)

const stringInput = { data: 'plain' }
t.assert.deepEqual(JSON.parse(stringify(stringInput)), stringInput)
})