StefanTerdell / zod-to-json-schema

Converts Zod schemas to Json schemas
ISC License
854 stars 67 forks source link

How can I specify the format? #95

Closed thelinuxlich closed 4 months ago

thelinuxlich commented 9 months ago

I want to specify a file upload format like described in https://swagger.io/docs/specification/describing-request-body/file-upload/ which needs to be binary. Is it possible to do this?

StefanTerdell commented 9 months ago

From what I can tell there's no native way to do that in Zod. You can open an issue or a PR in the Zod repo to add something like z.string().base64(). Then we can represent that as format: "binary" if the target is Open API.

thelinuxlich commented 9 months ago

I'd convert these to binary:

z.instanceof(File)
z.instanceof(Buffer)
z.instanceof(Blob)
StefanTerdell commented 9 months ago

There's no way to serialize an instanceof check unfortunately, and you're not describing the serialized data with that schema anyway. The base64 route is probably your best bet still

StefanTerdell commented 9 months ago

Added a PR over at Zod for a base64 check. I guess we'll see how that goes :) https://github.com/colinhacks/zod/pull/3047

StefanTerdell commented 4 months ago

Hello! A solution to this is now available as of 3.23.0. Since the schema is interpreted to represent the serialized data you can use z.string().base64() to represent file contents. By default this results in "contentEncoding": "base64" as described here but there's also an option ({ "base64Strategy": "format:binary" }) to set it to the OpenAPI <=3.0 equivalent

StefanTerdell commented 4 months ago

@thelinuxlich

thelinuxlich commented 4 months ago

Hey Stefan, this is great! Finally we can represent this type with Zod!