From f5bb456ffae6d2858a1ee2d19a408d1b03df9a4d Mon Sep 17 00:00:00 2001 From: Ahmed Yarub Hani Al Nuaimi <60621547+ahmedalnuaimi@users.noreply.github.com> Date: Mon, 17 Oct 2022 20:22:43 -0300 Subject: [PATCH] feat(example): set discriminated properties to mapped value (#8213) --- src/core/plugins/samples/fn.js | 15 +++++- test/unit/core/plugins/samples/fn.js | 68 ++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/src/core/plugins/samples/fn.js b/src/core/plugins/samples/fn.js index a6988d2c1f6..04fad9f1020 100644 --- a/src/core/plugins/samples/fn.js +++ b/src/core/plugins/samples/fn.js @@ -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++ } } diff --git a/test/unit/core/plugins/samples/fn.js b/test/unit/core/plugins/samples/fn.js index a456a4bf0f4..7bb04184ade 100644 --- a/test/unit/core/plugins/samples/fn.js +++ b/test/unit/core/plugins/samples/fn.js @@ -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",