From e179727cc7a489444c42c2162d0c553f3f209963 Mon Sep 17 00:00:00 2001 From: abonifacio Date: Mon, 12 Jul 2021 22:15:29 -0300 Subject: [PATCH] support required at root level --- src/scripts/import-open-api.ts | 20 ++++++++++++++++++-- src/scripts/tests/import-open-api.test.ts | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/scripts/import-open-api.ts b/src/scripts/import-open-api.ts index 431c17b..53ea578 100644 --- a/src/scripts/import-open-api.ts +++ b/src/scripts/import-open-api.ts @@ -116,6 +116,10 @@ export const getArray = (item: SchemaObject): string => { return `${item_type}[]`; }; +const requireProperties = (type: string, toRequire: string[]) => { + return `Require<${type}, ${toRequire.map(property => `"${property}"`).join(" | ")}>`; +}; + /** * Return the output type from an object * @@ -127,11 +131,19 @@ export const getObject = (item: SchemaObject): string => { } if (item.allOf) { - return item.allOf.map(resolveValue).join(" & "); + const composedType = item.allOf.map(resolveValue).join(" & "); + if (item.required) { + return requireProperties(composedType, item.required); + } + return composedType; } if (item.oneOf) { - return item.oneOf.map(resolveValue).join(" | "); + const unionType = item.oneOf.map(resolveValue).join(" | "); + if (item.required) { + return requireProperties(unionType, item.required); + } + return unionType; } if (!item.type && !item.properties && !item.additionalProperties) { @@ -882,6 +894,10 @@ import { ${imports.join(", ")} } from "restful-react"; outputHeaders += `\n${customImport}\n`; } + if (output.match(/Require = T & Required>;\n"; + } + if (pathParametersEncodingMode) { outputHeaders += `${getEncodingFunction(pathParametersEncodingMode)} diff --git a/src/scripts/tests/import-open-api.test.ts b/src/scripts/tests/import-open-api.test.ts index 6cb0ea0..8837ae3 100644 --- a/src/scripts/tests/import-open-api.test.ts +++ b/src/scripts/tests/import-open-api.test.ts @@ -352,6 +352,24 @@ describe("scripts/import-open-api", () => { `); }); + it("should deal with allOf and required at root level", () => { + const item = { + type: "object", + allOf: [{ $ref: "#/components/schemas/foo" }, { $ref: "#/components/schemas/bar" }], + required: ["a_bar_property", "a_foo_property"], + }; + expect(getObject(item)).toEqual(`Require`); + }); + + it("should deal with oneOf and required at root level", () => { + const item = { + type: "object", + oneOf: [{ $ref: "#/components/schemas/foo" }, { $ref: "#/components/schemas/bar" }], + required: ["a_common_property"], + }; + expect(getObject(item)).toEqual(`Require`); + }); + it("should deal with oneOf with null", () => { const item = { type: "object", @@ -364,6 +382,7 @@ describe("scripts/import-open-api", () => { }; expect(getObject(item)).toMatchInlineSnapshot(`"Foo | null"`); }); + it("should handle empty properties (1)", () => { const item = { properties: {},