Skip to content
This repository has been archived by the owner on Nov 11, 2023. It is now read-only.

Commit

Permalink
added type mapping for null
Browse files Browse the repository at this point in the history
  • Loading branch information
cmaus-cs authored and fabien0102 committed Jun 15, 2020
1 parent 5320dea commit 3e6a939
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 59 deletions.
121 changes: 62 additions & 59 deletions src/scripts/import-open-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ export const getScalar = (item: SchemaObject) => {
case "array":
return getArray(item) + nullable;

case "null":
return "null";

case "string":
case "byte":
case "binary":
Expand Down Expand Up @@ -161,7 +164,7 @@ export const getObject = (item: SchemaObject): string => {
}
output += ` [key: string]: ${
item.additionalProperties === true ? "any" : resolveValue(item.additionalProperties)
};`;
};`;
}

if (item.properties || item.additionalProperties) {
Expand Down Expand Up @@ -366,9 +369,9 @@ export const generateRestfulComponent = (
const lastParamInTheRouteDefinition =
operation.parameters && lastParamInTheRoute
? (operation.parameters.find(p => {
if (isReference(p)) return false;
return p.name === lastParamInTheRoute;
}) as ParameterObject | undefined) // Reference is not possible
if (isReference(p)) return false;
return p.name === lastParamInTheRoute;
}) as ParameterObject | undefined) // Reference is not possible
: { schema: { type: "string" } };

if (!lastParamInTheRouteDefinition) {
Expand All @@ -379,38 +382,38 @@ export const generateRestfulComponent = (
!isReference(lastParamInTheRouteDefinition.schema) && lastParamInTheRouteDefinition.schema
? getScalar(lastParamInTheRouteDefinition.schema)
: isReference(lastParamInTheRouteDefinition.schema)
? getRef(lastParamInTheRouteDefinition.schema.$ref)
: "string";
? getRef(lastParamInTheRouteDefinition.schema.$ref)
: "string";

const genericsTypes =
verb === "get"
? `${needAResponseComponent ? componentName + "Response" : responseTypes}, ${errorTypes}, ${
queryParamsType ? componentName + "QueryParams" : "void"
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`
queryParamsType ? componentName + "QueryParams" : "void"
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`
: `${needAResponseComponent ? componentName + "Response" : responseTypes}, ${errorTypes}, ${
queryParamsType ? componentName + "QueryParams" : "void"
}, ${
verb === "delete" && lastParamInTheRoute
? lastParamInTheRouteType
: needARequestBodyComponent
? componentName + "RequestBody"
: requestBodyTypes
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`;
queryParamsType ? componentName + "QueryParams" : "void"
}, ${
verb === "delete" && lastParamInTheRoute
? lastParamInTheRouteType
: needARequestBodyComponent
? componentName + "RequestBody"
: requestBodyTypes
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`;

const genericsTypesForHooksProps =
verb === "get"
? `${needAResponseComponent ? componentName + "Response" : responseTypes}, ${
queryParamsType ? componentName + "QueryParams" : "void"
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`
queryParamsType ? componentName + "QueryParams" : "void"
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`
: `${needAResponseComponent ? componentName + "Response" : responseTypes}, ${
queryParamsType ? componentName + "QueryParams" : "void"
}, ${
verb === "delete" && lastParamInTheRoute
? lastParamInTheRouteType
: needARequestBodyComponent
? componentName + "RequestBody"
: requestBodyTypes
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`;
queryParamsType ? componentName + "QueryParams" : "void"
}, ${
verb === "delete" && lastParamInTheRoute
? lastParamInTheRouteType
: needARequestBodyComponent
? componentName + "RequestBody"
: requestBodyTypes
}, ${paramsInPath.length ? componentName + "PathParams" : "void"}`;

const customPropsEntries = Object.entries(customProps);

Expand All @@ -424,51 +427,51 @@ export const generateRestfulComponent = (
needAResponseComponent
? `
export ${
responseTypes.includes("|") ? `type ${componentName}Response =` : `interface ${componentName}Response`
} ${responseTypes}
responseTypes.includes("|") ? `type ${componentName}Response =` : `interface ${componentName}Response`
} ${responseTypes}
`
: ""
}${
}${
queryParamsType
? `
export interface ${componentName}QueryParams {
${queryParamsType};
}
`
: ""
}${
}${
paramsInPath.length
? `
export interface ${componentName}PathParams {
${paramsTypes}
}
`
: ""
}${
}${
needARequestBodyComponent
? `
export interface ${componentName}RequestBody ${requestBodyTypes}
`
: ""
}
}
export type ${componentName}Props = Omit<${Component}Props<${genericsTypes}>, "path"${
verb === "get" ? "" : ` | "verb"`
}>${paramsInPath.length ? ` & ${componentName}PathParams` : ""};
}>${paramsInPath.length ? ` & ${componentName}PathParams` : ""};
${description}export const ${componentName} = (${
paramsInPath.length ? `{${paramsInPath.join(", ")}, ...props}` : "props"
}: ${componentName}Props) => (
}: ${componentName}Props) => (
<${Component}<${genericsTypes}>${
verb === "get"
? ""
: `
verb="${verb.toUpperCase()}"`
}
}
path={\`${route}\`}${
customPropsEntries.length
? "\n " + customPropsEntries.map(([key, value]) => `${key}=${value}`).join("\n ")
: ""
}
}
{...props}
/>
);
Expand All @@ -478,27 +481,27 @@ ${description}export const ${componentName} = (${
// Hooks version
output += `export type Use${componentName}Props = Omit<Use${Component}Props<${genericsTypesForHooksProps}>, "path"${
verb === "get" ? "" : ` | "verb"`
}>${paramsInPath.length ? ` & ${componentName}PathParams` : ""};
}>${paramsInPath.length ? ` & ${componentName}PathParams` : ""};
${description}export const use${componentName} = (${
paramsInPath.length ? `{${paramsInPath.join(", ")}, ...props}` : "props"
}: Use${componentName}Props) => use${Component}<${genericsTypes}>(${
}: Use${componentName}Props) => use${Component}<${genericsTypes}>(${
verb === "get" ? "" : `"${verb.toUpperCase()}", `
}${
}${
paramsInPath.length
? `({ ${paramsInPath.join(", ")} }: ${componentName}PathParams) => \`${route}\``
: `\`${route}\``
}, ${
}, ${
customPropsEntries.length || paramsInPath.length
? `{ ${
customPropsEntries.length
? `${customPropsEntries
.map(([key, value]) => `${key}:${reactPropsValueToObjectValue(value || "")}`)
.join(", ")},`
: ""
}${paramsInPath.length ? `pathParams: { ${paramsInPath.join(", ")} },` : ""} ...props }`
customPropsEntries.length
? `${customPropsEntries
.map(([key, value]) => `${key}:${reactPropsValueToObjectValue(value || "")}`)
.join(", ")},`
: ""
}${paramsInPath.length ? `pathParams: { ${paramsInPath.join(", ")} },` : ""} ...props }`
: "props"
});
});
`;

Expand All @@ -519,12 +522,12 @@ ${description}export const use${componentName} = (${
if (headerParams.map(({ name }) => name.toLocaleLowerCase()).includes("prefer")) {
output += `export type Poll${componentName}Props = Omit<PollProps<${genericsTypes}>, "path">${
paramsInPath.length ? ` & {${paramsTypes}}` : ""
};
};
${operation.summary ? `// ${operation.summary} (long polling)` : ""}
export const Poll${componentName} = (${
paramsInPath.length ? `{${paramsInPath.join(", ")}, ...props}` : "props"
}: Poll${componentName}Props) => (
}: Poll${componentName}Props) => (
<Poll<${genericsTypes}>
path={\`${route}\`}
{...props}
Expand Down Expand Up @@ -589,15 +592,15 @@ export const generateSchemasDefinition = (schemas: ComponentsObject["schemas"] =
Object.entries(schemas)
.map(([name, schema]) =>
!isReference(schema) &&
(!schema.type || schema.type === "object") &&
!schema.allOf &&
!schema.oneOf &&
!isReference(schema) &&
!schema.nullable
(!schema.type || schema.type === "object") &&
!schema.allOf &&
!schema.oneOf &&
!isReference(schema) &&
!schema.nullable
? generateInterface(name, schema)
: `${formatDescription(isReference(schema) ? undefined : schema.description)}export type ${pascal(
name,
)} = ${resolveValue(schema)};`,
name,
)} = ${resolveValue(schema)};`,
)
.join("\n\n") + "\n"
);
Expand Down Expand Up @@ -673,9 +676,9 @@ export interface ${pascal(name)}Response ${type}`;
export const formatDescription = (description?: string, tabSize = 0) =>
description
? `/**\n${description
.split("\n")
.map(i => `${" ".repeat(tabSize)} * ${i}`)
.join("\n")}\n${" ".repeat(tabSize)} */\n${" ".repeat(tabSize)}`
.split("\n")
.map(i => `${" ".repeat(tabSize)} * ${i}`)
.join("\n")}\n${" ".repeat(tabSize)} */\n${" ".repeat(tabSize)}`
: "";

/**
Expand Down
15 changes: 15 additions & 0 deletions src/scripts/tests/import-open-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ describe("scripts/import-open-api", () => {
{ item: { type: "string", nullable: true }, expected: "string | null" },
{ item: { type: "object", nullable: true }, expected: "{[key: string]: any} | null" },
{ item: { type: "object", $ref: "#/components/schemas/Foo", nullable: true }, expected: "Foo | null" },
{ item: { type: "null", nullable: true }, expected: "null" },
{ item: { type: "null" }, expected: "null" },
].map(({ item, expected }) =>
it(`should return ${expected} as type for ${item.type}`, () => {
expect(getScalar(item)).toEqual(expected);
Expand Down Expand Up @@ -331,6 +333,19 @@ describe("scripts/import-open-api", () => {
}"
`);
});

it("should deal with oneOf with null", () => {
const item = {
type: "object",
oneOf: [
{ $ref: "#/components/schemas/foo" },
{
type: "null",
},
],
};
expect(getObject(item)).toMatchInlineSnapshot(`"Foo | null"`);
});
it("should handle empty properties (1)", () => {
const item = {
properties: {},
Expand Down

0 comments on commit 3e6a939

Please sign in to comment.