@@ -3,6 +3,7 @@ import {generationLib} from "../generation-lib"
33import type { InputConfig } from "../input"
44import { logger } from "../logger"
55import type {
6+ Discriminator ,
67 Reference ,
78 Schema ,
89 SchemaNumber ,
@@ -191,7 +192,11 @@ export class SchemaNormalizer {
191192 { ...base , nullable} ,
192193 hasOwnProperties ? [ ...allOf , result ] : allOf ,
193194 )
194- const maybeUnion = this . union ( { ...base , nullable} , [ ...oneOf , ...anyOf ] )
195+ const maybeUnion = this . union (
196+ { ...base , nullable} ,
197+ [ ...oneOf , ...anyOf ] ,
198+ schemaObject . discriminator ,
199+ )
195200
196201 if ( maybeIntersection && maybeUnion ) {
197202 return this . intersection ( { ...base , nullable} , [
@@ -375,6 +380,29 @@ export class SchemaNormalizer {
375380 }
376381 }
377382
383+ private normalizeDiscriminator (
384+ discriminator : Discriminator | undefined ,
385+ ) : IRModelUnion [ "discriminator" ] | undefined {
386+ if ( ! discriminator ) {
387+ return undefined
388+ }
389+
390+ if ( ! discriminator . mapping ) {
391+ // todo: cna we support this if the discriminated property is an enum of one element?
392+ logger . warn ( "discriminators without a mapping are ignored." )
393+ return undefined
394+ }
395+
396+ return {
397+ propertyName : discriminator . propertyName ,
398+ mapping : Object . fromEntries (
399+ Object . entries ( discriminator . mapping ) . map ( ( [ key , value ] ) => {
400+ return [ key , { $ref : value } ]
401+ } ) ,
402+ ) ,
403+ }
404+ }
405+
378406 private normalizeComposition (
379407 items : ( Schema | Reference ) [ ] = [ ] ,
380408 parent : SchemaObject ,
@@ -511,6 +539,7 @@ export class SchemaNormalizer {
511539 private union (
512540 base : IRModelBase ,
513541 schemas : MaybeIRModel [ ] ,
542+ discriminator : Discriminator | undefined ,
514543 ) : MaybeIRModel | IRModelUnion | undefined {
515544 // (A|B)|(C|D) is the same as (A|B|C|D)
516545 // todo: merge repeated in-line schemas
@@ -530,6 +559,7 @@ export class SchemaNormalizer {
530559 return {
531560 ...base ,
532561 type : "union" ,
562+ discriminator : this . normalizeDiscriminator ( discriminator ) ,
533563 schemas,
534564 }
535565 }
0 commit comments