Skip to content

Commit 9c0687e

Browse files
committed
feat: parsing File type in convertToOpenAPI
1 parent 501814d commit 9c0687e

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

src/core/zod-to-openapi.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,25 @@
11
import zodToJsonSchema from "zod-to-json-schema";
2+
import { isFile } from "~/utils/zod-schema";
23
import type { SchemaObject } from "@omer-x/openapi-types/schema";
3-
import type { ZodType } from "zod";
4+
import type { ZodObject, ZodType } from "zod";
45

56
export default function convertToOpenAPI(schema: ZodType<unknown>, isArray: boolean) {
67
const result = zodToJsonSchema(isArray ? schema.array() : schema, {
78
target: "openApi3",
89
$refStrategy: "none",
9-
});
10-
return result as SchemaObject;
10+
}) as SchemaObject;
11+
if (result.type === "object" && result.properties) {
12+
// eslint-disable-next-line @typescript-eslint/ban-types
13+
for (const [propName, prop] of Object.entries<ZodType>((schema as ZodObject<{}>).shape)) {
14+
if (isFile(prop)) {
15+
result.properties[propName] = {
16+
type: "string",
17+
format: "binary",
18+
description: prop.description,
19+
// contentEncoding: "base64", // swagger-ui-react doesn't support this
20+
};
21+
}
22+
}
23+
}
24+
return result;
1125
}

src/utils/zod-schema.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { describe, expect, it } from "@jest/globals";
2+
import z from "zod";
3+
import { isFile } from "./zod-schema";
4+
5+
describe("isFile", () => {
6+
it("should return true for a valid file schema", () => {
7+
const fileSchema = z.instanceof(File);
8+
const result = isFile(fileSchema);
9+
expect(result).toBe(true);
10+
});
11+
12+
it("should return false for a non-File type in schema", () => {
13+
expect(isFile(z.string())).toBe(false);
14+
expect(isFile(z.number())).toBe(false);
15+
});
16+
});

src/utils/zod-schema.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import type { ZodType } from "zod";
2+
3+
export function isFile(schema: ZodType<unknown>) {
4+
const result = schema.safeParse(new File([], "nothing.txt"));
5+
return result.success;
6+
}

0 commit comments

Comments
 (0)