Skip to content

Commit

Permalink
feat: add support for explicit discriminators
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael M committed Oct 27, 2023
1 parent 489ffae commit 0da326f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
46 changes: 46 additions & 0 deletions packages/ng-openapi-gen/src/lib/utils/open-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ export function tsTypeVal(
let result = '{\n';
const properties = schema.properties || {};
const required = schema.required;

for (const baseSchema of allOf) {
const discriminator = tryGetDiscriminator(baseSchema, schema, openApi);
if (discriminator) {
result += `'${discriminator.propName}': '${discriminator.value}';\n`;
}
}

for (const [propName, property] of Object.entries(properties)) {
if (!property) {
continue;
Expand Down Expand Up @@ -178,3 +186,41 @@ export function resolveRef(openApi: OpenAPIObject, ref: string): unknown {
}
return current;
}

/** Tries to get a discriminator info from a base schema and for a derived one */
function tryGetDiscriminator(
baseSchemaOrRef: SchemaObject | ReferenceObject,
derivedSchema: SchemaObject,
openApi: OpenAPIObject,
) {
const baseSchema = (
baseSchemaOrRef.$ref ? resolveRef(openApi, baseSchemaOrRef.$ref) : baseSchemaOrRef
) as SchemaObject;
const discriminatorProp = baseSchema.discriminator?.propertyName;
if (discriminatorProp) {
const discriminatorValue = tryGetDiscriminatorValue(baseSchema, derivedSchema, openApi);
if (discriminatorValue) {
return {
propName: discriminatorProp,
value: discriminatorValue,
};
}
}
return;
}

/** Tries to get a discriminator value from a base schema and for a derived one */
function tryGetDiscriminatorValue(
baseSchema: SchemaObject,
derivedSchema: SchemaObject,
openApi: OpenAPIObject,
): string | null {
const mapping = baseSchema.discriminator?.mapping;

if (mapping) {
const mappingIndex = Object.values(mapping).findIndex((ref) => resolveRef(openApi, ref) === derivedSchema);
return Object.keys(mapping)[mappingIndex] ?? null;
}

return null;
}
2 changes: 1 addition & 1 deletion packages/ng-openapi-gen/src/lib/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function escapeId(name: string) {
/** Returns the TypeScript comments for the given schema description, in a given indentation level */
export function tsComments(description: string | undefined, level: number, deprecated?: boolean): string {
const indent = ' '.repeat(level);
if (description == undefined || description.length === 0) {
if (description === undefined || description.length === 0) {
return indent + (deprecated ? '/** @deprecated */' : '');
}
const lines = description.trim().split('\n');
Expand Down

0 comments on commit 0da326f

Please sign in to comment.