Skip to content

Commit

Permalink
feat(example): set discriminated properties to mapped value (#8213)
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmedalnuaimi authored Oct 17, 2022
1 parent 7936ec9 commit f5bb456
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/core/plugins/samples/fn.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,20 @@ export const sampleFromSchemaGeneric = (schema, config={}, exampleOverride = und
if(!canAddProperty(propName)) {
return
}
res[propName] = sampleFromSchemaGeneric(props[propName], config, overrideE, respectXML)
if(Object.prototype.hasOwnProperty.call(schema, "discriminator") &&
schema.discriminator &&
Object.prototype.hasOwnProperty.call(schema.discriminator, "mapping") &&
schema.discriminator.mapping &&
schema.discriminator.propertyName === propName) {
for (let pair in schema.discriminator.mapping){
if (schema.$$ref.search(schema.discriminator.mapping[pair]) !== -1) {
res[propName] = pair
break
}
}
} else {
res[propName] = sampleFromSchemaGeneric(props[propName], config, overrideE, respectXML)
}
propertyAddedCounter++
}
}
Expand Down
68 changes: 68 additions & 0 deletions test/unit/core/plugins/samples/fn.js
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,74 @@ describe("sampleFromSchema", () => {
})
})

describe("discriminator mapping example", () => {
it("returns an example where discriminated field is equal to mapping value", () => {
let definition = {
"type": "array",
"items": {
"oneOf": [
{
"required": [
"type"
],
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"TYPE1",
"TYPE2"
]
}
},
"discriminator": {
"propertyName": "type",
"mapping": {
"TYPE1": "#/components/schemas/FirstDto",
"TYPE2": "#/components/schemas/SecondDto"
}
},
"$$ref": "examples/swagger-config.yaml#/components/schemas/FirstDto"
},
{
"required": [
"type"
],
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"TYPE1",
"TYPE2"
]
}
},
"discriminator": {
"propertyName": "type",
"mapping": {
"TYPE1": "#/components/schemas/FirstDto",
"TYPE2": "#/components/schemas/SecondDto"
}
},
"$$ref": "examples/swagger-config.yaml#/components/schemas/SecondDto"
}
]
}
}

let expected = [
{
"type": "TYPE1"
}, {
"type": "TYPE2"
}
]

expect(sampleFromSchema(definition)).toEqual(expected)
})
})

it("should use overrideExample when defined", () => {
const definition = {
type: "object",
Expand Down

0 comments on commit f5bb456

Please sign in to comment.