Skip to content

Bugfix for discriminators using allOf #1578

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 30 additions & 14 deletions packages/openapi-typescript/examples/digital-ocean-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9881,18 +9881,26 @@ export interface components {
*/
type: "assign" | "unassign";
};
floating_ip_action_assign: {
type: "assign";
} & (Omit<components["schemas"]["floatingIPsAction"], "type"> & {
floating_ip_action_assign: Omit<components["schemas"]["floatingIPsAction"], "type"> & {
/**
* @description The ID of the Droplet that the floating IP will be assigned to.
* @example 758604968
*/
droplet_id: number;
});
floating_ip_action_unassign: {
} & {
/**
* @description discriminator enum property added by openapi-typescript
* @enum {string}
*/
type: "assign";
};
floating_ip_action_unassign: Omit<components["schemas"]["floatingIPsAction"], "type"> & Record<string, never> & {
/**
* @description discriminator enum property added by openapi-typescript
* @enum {string}
*/
type: "unassign";
} & (Omit<components["schemas"]["floatingIPsAction"], "type"> & Record<string, never>);
};
namespace_info: {
/**
* @description The namespace's API hostname. Each function in a namespace is provided an endpoint at the namespace's hostname.
Expand Down Expand Up @@ -11555,18 +11563,26 @@ export interface components {
*/
type: "assign" | "unassign";
};
reserved_ip_action_assign: {
type: "assign";
} & (Omit<components["schemas"]["reserved_ip_action_type"], "type"> & {
reserved_ip_action_assign: Omit<components["schemas"]["reserved_ip_action_type"], "type"> & {
/**
* @description The ID of the Droplet that the reserved IP will be assigned to.
* @example 758604968
*/
droplet_id: number;
});
reserved_ip_action_unassign: {
} & {
/**
* @description discriminator enum property added by openapi-typescript
* @enum {string}
*/
type: "assign";
};
reserved_ip_action_unassign: Omit<components["schemas"]["reserved_ip_action_type"], "type"> & Record<string, never> & {
/**
* @description discriminator enum property added by openapi-typescript
* @enum {string}
*/
type: "unassign";
} & (Omit<components["schemas"]["reserved_ip_action_type"], "type"> & Record<string, never>);
};
snapshots: {
/**
* @description The unique identifier for the snapshot.
Expand Down Expand Up @@ -19323,7 +19339,7 @@ export interface operations {
* */
requestBody?: {
content: {
"application/json": Omit<components["schemas"]["floating_ip_action_unassign"], "type"> | Omit<components["schemas"]["floating_ip_action_assign"], "type">;
"application/json": components["schemas"]["floating_ip_action_unassign"] | components["schemas"]["floating_ip_action_assign"];
};
};
responses: {
Expand Down Expand Up @@ -22367,7 +22383,7 @@ export interface operations {
* */
requestBody?: {
content: {
"application/json": Omit<components["schemas"]["reserved_ip_action_unassign"], "type"> | Omit<components["schemas"]["reserved_ip_action_assign"], "type">;
"application/json": components["schemas"]["reserved_ip_action_unassign"] | components["schemas"]["reserved_ip_action_assign"];
};
};
responses: {
Expand Down
37 changes: 25 additions & 12 deletions packages/openapi-typescript/scripts/update-examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,31 @@ async function generateSchemas() {
const updateSchema = async (name: string, ext: string) => {
const start = performance.now();

await execa(
"./bin/cli.js",
[`./examples/${name}${ext}`, "-o", `./examples/${name}.ts`],
{ cwd },
);

schemasDoneCount++;
const timeMs = Math.round(performance.now() - start);

console.log(
`✔︎ [${schemasDoneCount}/${schemaTotalCount}] Updated ${name} (${timeMs}ms)`,
);
try {
await execa(
"./bin/cli.js",
[`./examples/${name}${ext}`, "-o", `./examples/${name}.ts`],
{
cwd:
process.platform === "win32"
? // execa/cross-spawn can not handle URL objects on Windows, so convert it to string and cut away the protocol
cwd.toString().slice("file:///".length)
: cwd,
},
);

schemasDoneCount++;
const timeMs = Math.round(performance.now() - start);

console.log(
`✔︎ [${schemasDoneCount}/${schemaTotalCount}] Updated ${name} (${timeMs}ms)`,
);
} catch (error) {
console.error(
`✘ [${schemasDoneCount}/${schemaTotalCount}] Failed to update ${name}`,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice addition 👍

{ error: error instanceof Error ? error.message : error },
);
}
};

console.log("Updating examples...");
Expand Down
168 changes: 110 additions & 58 deletions packages/openapi-typescript/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,68 @@ function createDiscriminatorEnum(
};
}

/** Adds or replaces the discriminator enum with the passed `values` in a schema defined by `ref` */
function patchDiscriminatorEnum(
schema: SchemaObject,
ref: string,
values: string[],
discriminator: DiscriminatorObject,
discriminatorRef: string,
options: OpenAPITSOptions,
): boolean {
const resolvedSchema = resolveRef<SchemaObject>(schema, ref, {
silent: options.silent ?? false,
});

if (resolvedSchema?.allOf) {
// if the schema is an allOf, we can append a new schema object to the allOf array
resolvedSchema.allOf.push({
type: "object",
// discriminator enum properties always need to be required
required: [discriminator.propertyName],
properties: {
[discriminator.propertyName]: createDiscriminatorEnum(values),
},
});

return true;
} else if (
typeof resolvedSchema === "object" &&
"type" in resolvedSchema &&
resolvedSchema.type === "object"
) {
// if the schema is an object, we can apply the discriminator enums to its properties
if (!resolvedSchema.properties) {
resolvedSchema.properties = {};
}

// discriminator enum properties always need to be required
if (!resolvedSchema.required) {
resolvedSchema.required = [discriminator.propertyName];
} else if (!resolvedSchema.required.includes(discriminator.propertyName)) {
resolvedSchema.required.push(discriminator.propertyName);
}

// add/replace the discriminator enum property
resolvedSchema.properties[discriminator.propertyName] =
createDiscriminatorEnum(
values,
resolvedSchema.properties[discriminator.propertyName],
);

return true;
}

warn(
`Discriminator mapping has an invalid schema (neither an object schema nor an allOf array): ${ref} => ${values.join(
", ",
)} (Discriminator: ${discriminatorRef})`,
options.silent,
);

return false;
}

type InternalDiscriminatorMapping = Record<
string,
{ inferred?: string; defined?: string[] }
Expand Down Expand Up @@ -267,57 +329,18 @@ export function scanDiscriminators(
// the inferred enum values from the schema might not represent the actual enum values of the discriminator,
// so if we have defined values, use them instead
const mappedValues = defined ?? [inferred!];
const resolvedSchema = resolveRef<SchemaObject>(schema, mappedRef, {
silent: options.silent ?? false,
});

if (resolvedSchema?.allOf) {
// if the schema is an allOf, we can append a new schema object to the allOf array
resolvedSchema.allOf.push({
type: "object",
// discriminator enum properties always need to be required
required: [discriminator.propertyName],
properties: {
[discriminator.propertyName]: createDiscriminatorEnum(mappedValues),
},
});

refsHandled.push(mappedRef);
} else if (
typeof resolvedSchema === "object" &&
"type" in resolvedSchema &&
resolvedSchema.type === "object"
if (
patchDiscriminatorEnum(
schema,
mappedRef,
mappedValues,
discriminator,
ref,
options,
)
) {
// if the schema is an object, we can apply the discriminator enums to its properties
if (!resolvedSchema.properties) {
resolvedSchema.properties = {};
}

// discriminator enum properties always need to be required
if (!resolvedSchema.required) {
resolvedSchema.required = [discriminator.propertyName];
} else if (
!resolvedSchema.required.includes(discriminator.propertyName)
) {
resolvedSchema.required.push(discriminator.propertyName);
}

// add/replace the discriminator enum property
resolvedSchema.properties[discriminator.propertyName] =
createDiscriminatorEnum(
mappedValues,
resolvedSchema.properties[discriminator.propertyName],
);

refsHandled.push(mappedRef);
} else {
warn(
`Discriminator mapping has an invalid schema (neither an object schema nor an allOf array): ${mappedRef} => ${mappedValues.join(
", ",
)} (Discriminator: ${ref})`,
options.silent,
);
continue;
}
}
});
Expand All @@ -326,19 +349,48 @@ export function scanDiscriminators(
// (sometimes this mapping is implicit, so it can’t be done until we know
// about every discriminator in the document)
walk(schema, (obj, path) => {
for (const key of ["oneOf", "anyOf", "allOf"] as const) {
if (obj && Array.isArray(obj[key])) {
for (const item of (obj as any)[key]) {
if ("$ref" in item) {
if (objects[item.$ref]) {
objects[createRef(path)] = {
...objects[item.$ref],
};
if (!obj || !Array.isArray(obj.allOf)) {
return;
}

for (const item of (obj as any).allOf) {
if ("$ref" in item) {
if (!objects[item.$ref]) {
return;
}

const ref = createRef(path);
const discriminator = objects[item.$ref];
const mappedValues: string[] = [];

if (discriminator.mapping) {
for (const mappedValue in discriminator.mapping) {
if (discriminator.mapping[mappedValue] === ref) {
mappedValues.push(mappedValue);
}
}

if (mappedValues.length > 0) {
if (
patchDiscriminatorEnum(
schema,
ref,
mappedValues,
discriminator,
item.$ref,
options,
)
) {
refsHandled.push(ref);
}
} else if (item.discriminator?.propertyName) {
objects[createRef(path)] = { ...item.discriminator };
}
}

objects[ref] = {
...objects[item.$ref],
};
} else if (item.discriminator?.propertyName) {
objects[createRef(path)] = { ...item.discriminator };
}
}
});
Expand Down
Loading
Loading