Skip to content

Always checks for required properties, even if they are missing from properties #620

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 2 commits into from
Jun 14, 2021
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
20 changes: 18 additions & 2 deletions src/transform/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ export function transformSchemaObjMap(obj: Record<string, any>, options: Transfo
return output.replace(/\n+$/, "\n"); // replace repeat line endings with only one
}

/** make sure all required fields exist **/
export function addRequiredProps(properties: Record<string, any>, required: Set<string>): string[] {
const missingRequired = [...required].filter((r: string) => !(r in properties));
if (missingRequired.length == 0) {
return [];
}
let output = "";
for (const r of missingRequired) {
output += `${r}: unknown;\n`;
}
return [`{\n${output}}`];
}

/** transform anyOf */
export function transformAnyOf(anyOf: any, options: TransformSchemaObjOptions): string {
// filter out anyOf keys that only have a `required` key. #642
Expand Down Expand Up @@ -99,14 +112,16 @@ export function transformSchemaObj(node: any, options: TransformSchemaObjOptions
}
case "object": {
const isAnyOfOrOneOfOrAllOf = "anyOf" in node || "oneOf" in node || "allOf" in node;

const missingRequired = addRequiredProps(node.properties || {}, node.required || []);
// if empty object, then return generic map type
if (
!isAnyOfOrOneOfOrAllOf &&
(!node.properties || !Object.keys(node.properties).length) &&
!node.additionalProperties
) {
output += `{ ${readonly}[key: string]: any }`;
const emptyObj = `{ ${readonly}[key: string]: unknown }`;

output += tsIntersectionOf([emptyObj, ...missingRequired]);
break;
}

Expand Down Expand Up @@ -144,6 +159,7 @@ export function transformSchemaObj(node: any, options: TransformSchemaObjOptions
...(node.anyOf ? [transformAnyOf(node.anyOf, options)] : []),
...(node.oneOf ? [transformOneOf(node.oneOf, options)] : []),
...(properties ? [`{\n${properties}\n}`] : []), // then properties (line breaks are important!)
...missingRequired, // add required that are missing from properties
...(additionalProperties ? [additionalProperties] : []), // then additional properties
]);

Expand Down
41 changes: 37 additions & 4 deletions tests/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ describe("SchemaObject", () => {
);

// unknown
expect(transform(objUnknown, { ...defaults })).toBe(`{ [key: string]: any }`);
expect(transform(objUnknown, { ...defaults })).toBe(`{ [key: string]: unknown }`);

// empty
expect(transform({}, { ...defaults })).toBe(`{ [key: string]: any }`);
expect(transform({}, { ...defaults })).toBe(`{ [key: string]: unknown }`);

// nullable
expect(transform(objNullable, { ...defaults })).toBe(`({\n"string"?: string;\n\n}) | null`);
Expand All @@ -73,8 +73,8 @@ describe("SchemaObject", () => {
expect(transform(objStd, opts)).toBe(
`{\nreadonly "object"?: {\nreadonly "string"?: string;\nreadonly "number"?: components["schemas"]["object_ref"];\n\n};\n\n}`
);
expect(transform(objUnknown, opts)).toBe(`{ readonly [key: string]: any }`);
expect(transform({}, opts)).toBe(`{ readonly [key: string]: any }`);
expect(transform(objUnknown, opts)).toBe(`{ readonly [key: string]: unknown }`);
expect(transform({}, opts)).toBe(`{ readonly [key: string]: unknown }`);
expect(transform(objNullable, opts)).toBe(`({\nreadonly "string"?: string;\n\n}) | null`);
expect(transform(objRequired, opts)).toBe(`{\nreadonly "required": string;\nreadonly "optional"?: boolean;\n\n}`);
});
Expand Down Expand Up @@ -368,6 +368,39 @@ describe("SchemaObject", () => {
}"
`);
});
it("empty object with required fields", () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Awesome tests! ✨

expect(
transform(
{
type: "object",
required: ["abc"],
},
{ ...defaults }
)
).toBe(`({ [key: string]: unknown }) & ({
abc: unknown;
})`);
});
});

it("object with missing required fields", () => {
expect(
transform(
{
type: "object",
required: ["abc", "email"],
properties: {
email: { type: "string" },
},
},
{ ...defaults }
)
).toBe(`({
"email": string;

}) & ({
abc: unknown;
})`);
});

describe("comments", () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/v2/expected/petstore.immutable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ export interface operations {
/** Additional data to pass to server */
readonly additionalMetadata?: string;
/** file to upload */
readonly file?: { readonly [key: string]: any };
readonly file?: { readonly [key: string]: unknown };
};
};
readonly responses: {
Expand Down
2 changes: 1 addition & 1 deletion tests/v2/expected/petstore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ export interface operations {
/** Additional data to pass to server */
additionalMetadata?: string;
/** file to upload */
file?: { [key: string]: any };
file?: { [key: string]: unknown };
};
};
responses: {
Expand Down
Loading