Skip to content

Commit 69a9c84

Browse files
authored
Support fully-qualified refs as discriminator mapping values (#1017)
* Use discriminator mapping key as property value Fixes #1016 * Fix lint errors * Accept either fully-qualified ref or schema name (fixes test failure)
1 parent 79944f4 commit 69a9c84

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/transform/schema-object.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,10 @@ export function defaultSchemaObjectTransform(
205205
const discriminator = ctx.discriminators[discriminatorRef.$ref];
206206
let value = parseRef(path).path.pop() as string;
207207
if (discriminator.mapping) {
208-
const matchedValue = Object.entries(discriminator.mapping).find(([_, v]) => v === value);
208+
// Mapping value can either be a fully-qualified ref (#/components/schemas/XYZ) or a schema name (XYZ)
209+
const matchedValue = Object.entries(discriminator.mapping).find(
210+
([_, v]) => (v[0] !== "#" && v === value) || (v[0] === "#" && parseRef(v).path.pop() === value)
211+
);
209212
if (matchedValue) value = matchedValue[0]; // why was this designed backwards!?
210213
}
211214
coreType.unshift(indent(`${discriminator.propertyName}: ${escStr(value)};`, indentLv + 1));

test/schema-object.test.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,35 @@ describe("Schema Object", () => {
246246
number: number;
247247
}]>`);
248248
});
249+
250+
test("discriminator", () => {
251+
const schema: SchemaObject = {
252+
type: "object",
253+
allOf: [
254+
{ $ref: 'components["schemas"]["parent"]' },
255+
{ type: "object", properties: { string: { type: "string" } } },
256+
],
257+
};
258+
const generated = transformSchemaObject(schema, {
259+
path: options.path,
260+
ctx: {
261+
...options.ctx,
262+
discriminators: {
263+
'components["schemas"]["parent"]': {
264+
propertyName: "operation",
265+
mapping: {
266+
test: options.path,
267+
},
268+
},
269+
},
270+
},
271+
});
272+
expect(generated).toBe(`{
273+
operation: "test";
274+
} & Omit<components["schemas"]["parent"], "operation"> & {
275+
string?: string;
276+
}`);
277+
});
249278
});
250279

251280
describe("allOf", () => {

0 commit comments

Comments
 (0)