Skip to content
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

Fix path params to use schema types #298

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
37 changes: 5 additions & 32 deletions lib/src/getZodiosEndpointDefinitionList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import type { CodeMeta, ConversionTypeContext } from "./CodeMeta";
import { getOpenApiDependencyGraph } from "./getOpenApiDependencyGraph";
import { isReferenceObject } from "./isReferenceObject";
import { makeSchemaResolver } from "./makeSchemaResolver";
import { getZodChain, getZodSchema } from "./openApiToZod";
import { getZodSchema } from "./openApiToZod";
import { getSchemaComplexity } from "./schema-complexity";
import type { TemplateContext } from "./template-context";
import {
Expand Down Expand Up @@ -202,14 +202,7 @@ export const getZodiosEndpointDefinitionList = (doc: OpenAPIObject, options?: Te
name: "body",
type: "Body",
description: requestBody.description!,
schema:
getZodVarName(bodyCode, operationName + "_Body") +
getZodChain({
schema: isReferenceObject(bodySchema)
? ctx.resolver.getSchemaByRef(bodySchema.$ref)
: bodySchema,
meta: bodyCode.meta,
}),
schema: getZodVarName(bodyCode, operationName + "_Body"),
});
}
}
Expand Down Expand Up @@ -275,13 +268,7 @@ export const getZodiosEndpointDefinitionList = (doc: OpenAPIObject, options?: Te
.with("query", () => "Query")
.with("path", () => "Path")
.run() as "Header" | "Query" | "Path",
schema: getZodVarName(
paramCode.assign(
paramCode.toString() +
getZodChain({ schema: paramSchema, meta: paramCode.meta, options })
),
paramItem.name
),
schema: getZodVarName(paramCode.assign(paramCode.toString()), paramItem.name),
});
}
}
Expand All @@ -307,14 +294,7 @@ export const getZodiosEndpointDefinitionList = (doc: OpenAPIObject, options?: Te

if (maybeSchema) {
schema = getZodSchema({ schema: maybeSchema, ctx, meta: { isRequired: true }, options });
schemaString =
(schema.ref ? getZodVarName(schema) : schema.toString()) +
getZodChain({
schema: isReferenceObject(maybeSchema)
? ctx.resolver.getSchemaByRef(maybeSchema.$ref)
: maybeSchema,
meta: schema.meta,
});
schemaString = schema.ref ? getZodVarName(schema) : schema.toString();
}

if (endpointDefinition.responses !== undefined) {
Expand Down Expand Up @@ -363,14 +343,7 @@ export const getZodiosEndpointDefinitionList = (doc: OpenAPIObject, options?: Te

if (maybeSchema) {
schema = getZodSchema({ schema: maybeSchema, ctx, meta: { isRequired: true }, options });
schemaString =
(schema.ref ? getZodVarName(schema) : schema.toString()) +
getZodChain({
schema: isReferenceObject(maybeSchema)
? ctx.resolver.getSchemaByRef(maybeSchema.$ref)
: maybeSchema,
meta: schema.meta,
});
schemaString = schema.ref ? getZodVarName(schema) : schema.toString();
}

if (schemaString) {
Expand Down
30 changes: 14 additions & 16 deletions lib/src/openApiToZod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ test("getSchemaAsZodString", () => {
expect(getSchemaAsZodString({ type: "boolean" })).toMatchInlineSnapshot('"z.boolean()"');
expect(getSchemaAsZodString({ type: "string" })).toMatchInlineSnapshot('"z.string()"');
expect(getSchemaAsZodString({ type: "number" })).toMatchInlineSnapshot('"z.number()"');
expect(getSchemaAsZodString({ type: "integer" })).toMatchInlineSnapshot('"z.number()"');
expect(getSchemaAsZodString({ type: "integer" })).toMatchInlineSnapshot('"z.number().int()"');
// expect(getSchemaAsZodString({ type: "string", format: "date-time" })).toMatchInlineSnapshot('"z.string().datetime()"');
// expect(getSchemaAsZodString({ type: "number", nullable: true, minimum: 0 })).toMatchInlineSnapshot('"z.number().nullable().gte(0)"');

Expand Down Expand Up @@ -161,8 +161,8 @@ test("getSchemaAsZodString", () => {
type: "string",
},
},
}
]
},
],
},
{
type: "object",
Expand All @@ -180,11 +180,10 @@ test("getSchemaAsZodString", () => {
},
},
},
]
}
],
},
],
discriminator: { propertyName: "type" },

})
).toMatchInlineSnapshot(`
"
Expand Down Expand Up @@ -226,7 +225,7 @@ test("getSchemaAsZodString", () => {
},
},
},
]
],
},
{
type: "object",
Expand Down Expand Up @@ -257,13 +256,14 @@ test("getSchemaAsZodString", () => {
},
},
},
]
}
],
},
],
discriminator: { propertyName: "type" },

})
).toMatchInlineSnapshot('"z.union([z.object({ type: z.literal("a"), a: z.string() }).passthrough().and(z.object({ type: z.literal("c"), c: z.string() }).passthrough()), z.object({ type: z.literal("b"), b: z.string() }).passthrough().and(z.object({ type: z.literal("d"), d: z.string() }).passthrough())])"');
).toMatchInlineSnapshot(
'"z.union([z.object({ type: z.literal("a"), a: z.string() }).passthrough().and(z.object({ type: z.literal("c"), c: z.string() }).passthrough()), z.object({ type: z.literal("b"), b: z.string() }).passthrough().and(z.object({ type: z.literal("d"), d: z.string() }).passthrough())])"'
);

expect(
getSchemaAsZodString({
Expand All @@ -272,9 +272,7 @@ test("getSchemaAsZodString", () => {
anyOfExample: { anyOf: [{ type: "string" }, { type: "number" }] },
},
})
).toMatchInlineSnapshot(
'"z.object({ anyOfExample: z.union([z.string(), z.number()]) }).partial().passthrough()"'
);
).toMatchInlineSnapshot('"z.object({ anyOfExample: z.union([z.string(), z.number()]) }).partial().passthrough()"');

expect(
getSchemaAsZodString({
Expand All @@ -296,14 +294,14 @@ test("getSchemaAsZodString", () => {
});

test("getSchemaWithChainableAsZodString", () => {
expect(getSchemaAsZodString({ type: "string", nullable: true })).toMatchInlineSnapshot('"z.string()"');
expect(getSchemaAsZodString({ type: "string", nullable: true })).toMatchInlineSnapshot('"z.string().nullable()"');
expect(getSchemaAsZodString({ type: "string", nullable: false })).toMatchInlineSnapshot('"z.string()"');

expect(getSchemaAsZodString({ type: "string", nullable: false }, { isRequired: true })).toMatchInlineSnapshot(
'"z.string()"'
);
expect(getSchemaAsZodString({ type: "string", nullable: true }, { isRequired: true })).toMatchInlineSnapshot(
'"z.string()"'
'"z.string().nullable()"'
);
});

Expand Down
116 changes: 74 additions & 42 deletions lib/src/openApiToZod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,15 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
.join(", ")}])
`);
}

const chain = getZodChain({
schema,
meta: { ...code.meta, isRequired: code.meta.isRequired ?? true },
options,
});
return code.assign(
`z.union([${schema.oneOf.map((prop) => getZodSchema({ schema: prop, ctx, meta, options })).join(", ")}])`
`z.union([${schema.oneOf
.map((prop) => getZodSchema({ schema: prop, ctx, meta, options }))
.join(", ")}])${chain}`
);
}

Expand Down Expand Up @@ -129,8 +135,12 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
return type.toString();
})
.join(", ");

return code.assign(`z.union([${types}])`);
const chain = getZodChain({
schema,
meta: { ...code.meta, isRequired: code.meta.isRequired ?? true },
options,
});
return code.assign(`z.union([${types}])${chain}`);
}

if (schema.allOf) {
Expand Down Expand Up @@ -167,17 +177,24 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option

const schemaType = schema.type ? (schema.type.toLowerCase() as NonNullable<typeof schema.type>) : undefined;
if (schemaType && isPrimitiveType(schemaType)) {
const chain = getZodChain({
schema,
meta: { ...code.meta, isRequired: code.meta.isRequired ?? true },
options,
});
if (schema.enum) {
if (schemaType === "string") {
if (schema.enum.length === 1) {
const value = schema.enum[0];
const valueString = value === null ? "null" : `"${value}"`;
return code.assign(`z.literal(${valueString})`);
return code.assign(`z.literal(${valueString})${chain}`);
}

// eslint-disable-next-line sonarjs/no-nested-template-literals
return code.assign(
`z.enum([${schema.enum.map((value) => (value === null ? "null" : `"${value}"`)).join(", ")}])`
`z.enum([${schema.enum
.map((value) => (value === null ? "null" : `"${value}"`))
.join(", ")}])${chain}`
);
}

Expand All @@ -187,37 +204,42 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option

if (schema.enum.length === 1) {
const value = schema.enum[0];
return code.assign(`z.literal(${value === null ? "null" : value})`);
return code.assign(`z.literal(${value === null ? "null" : value})${chain}`);
}

return code.assign(
// eslint-disable-next-line sonarjs/no-nested-template-literals
`z.union([${schema.enum.map((value) => `z.literal(${value === null ? "null" : value})`).join(", ")}])`
`z.union([${schema.enum
.map((value) => `z.literal(${value === null ? "null" : value})`)
.join(", ")}])${chain}`
);
}

return code.assign(
match(schemaType)
.with("integer", () => "z.number()")
.with("string", () =>
match(schema.format)
.with("binary", () => "z.instanceof(File)")
.otherwise(() => "z.string()")
)
.otherwise((type) => `z.${type}()`)
);
const type = match(schemaType)
.with("integer", () => "z.number()")
.with("string", () =>
match(schema.format)
.with("binary", () => "z.instanceof(File)")
.otherwise(() => "z.string()")
)
.otherwise((type) => `z.${type}()`);
return code.assign(type + chain);
}

const readonly = options?.allReadonly ? ".readonly()" : "";

if (schemaType === "array") {
const chain = getZodChain({
schema,
meta: { ...code.meta, isRequired: code.meta.isRequired ?? true },
options,
});
if (schema.items) {
return code.assign(
`z.array(${getZodSchema({ schema: schema.items, ctx, meta, options }).toString()})${readonly}`
`z.array(${getZodSchema({ schema: schema.items, ctx, meta, options }).toString()})${readonly}${chain}`
);
}

return code.assign(`z.array(z.any())${readonly}`);
return code.assign(`z.array(z.any())${readonly}${chain}`);
}

if (schemaType === "object" || schema.properties || schema.additionalProperties) {
Expand All @@ -231,15 +253,18 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
const additionalPropsSchema = additionalProps === false ? "" : ".passthrough()";

if (typeof schema.additionalProperties === "object" && Object.keys(schema.additionalProperties).length > 0) {
const chain = getZodChain({
schema,
meta: { ...code.meta, isRequired: code.meta.isRequired ?? true },
options,
});
return code.assign(
`z.record(${(
getZodSchema({ schema: schema.additionalProperties, ctx, meta, options }) +
getZodChain({
schema: schema.additionalProperties as SchemaObject,
meta: { ...meta, isRequired: true },
options,
})
).toString()})`
`z.record(${getZodSchema({
schema: schema.additionalProperties,
ctx,
meta,
options,
}).toString()})${chain}`
);
}

Expand All @@ -259,20 +284,17 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
name: prop,
} as CodeMetaData;

let propActualSchema = propSchema;

const zodSchema = getZodSchema({ schema: propSchema, ctx, meta: propMetadata, options });
if (isReferenceObject(propSchema) && ctx?.resolver) {
propActualSchema = ctx.resolver.getSchemaByRef(propSchema.$ref);
if (!propActualSchema) {
throw new Error(`Schema ${propSchema.$ref} not found`);
}
const chain = getZodChain({
schema,
meta: propMetadata,
options,
});
return [prop, zodSchema + chain];
}

const propCode =
getZodSchema({ schema: propSchema, ctx, meta: propMetadata, options }) +
getZodChain({ schema: propActualSchema as SchemaObject, meta: propMetadata, options });

return [prop, propCode.toString()];
return [prop, zodSchema.toString()];
});

properties =
Expand All @@ -283,10 +305,20 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option

const partial = isPartial ? ".partial()" : "";
const strict = options?.strictObjects ? ".strict()" : "";
return code.assign(`z.object(${properties})${partial}${strict}${additionalPropsSchema}${readonly}`);
const chain = getZodChain({
schema,
meta: { ...code.meta, isRequired: code.meta.isRequired ?? true },
options,
});
return code.assign(`z.object(${properties})${partial}${strict}${additionalPropsSchema}${readonly}${chain}`);
}

if (!schemaType) return code.assign("z.unknown()");
const chain = getZodChain({
schema,
meta: { ...code.meta, isRequired: code.meta.isRequired ?? true },
options,
});
if (!schemaType) return code.assign(`z.unknown()${chain}`);

// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Unsupported schema type: ${schemaType}`);
Expand Down
10 changes: 5 additions & 5 deletions lib/tests/allOf-oneOf-anyOf-single-ref.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ test("allOf-single-ref", async () => {
import { z } from "zod";

const MyComponent = z.enum(["one", "two", "three"]);
const allOf_ref_param = MyComponent.optional();
const allOf_ref_param = MyComponent;

export const schemas = {
MyComponent,
allOf_ref_param,
};

const endpoints = makeApi([
{
method: "get",
Expand All @@ -88,9 +88,9 @@ test("allOf-single-ref", async () => {
response: z.void(),
},
]);

export const api = new Zodios(endpoints);

export function createApiClient(baseUrl: string, options?: ZodiosOptions) {
return new Zodios(baseUrl, endpoints, options);
}
Expand Down
Loading