astahmer / openapi-zod-client

Generate a zodios (typescript http client with zod validation) from an OpenAPI spec (json/yaml)
openapi-zod-client.vercel.app
788 stars 84 forks source link

binary properties cause failure in server environments #225

Open s-h-a-d-o-w opened 1 year ago

s-h-a-d-o-w commented 1 year ago

Describe the bug When using the generated code in a server environment (which might obviously become common due to React server components), the following error is thrown: ReferenceError: File is not defined

Minimal reproduction See this branch: https://github.com/s-h-a-d-o-w/openapi-zod-client-experiment/tree/file-problem-repro

The error is emitted when running the dev server.

Expected behavior I believe the ideal solution would be to generate isomorphic code that looks like the following:

schema: z.custom<File | Buffer>((data) => {
  return typeof window === 'undefined' ? data instanceof Buffer : data instanceof File
}, 'Input is not an instance of a Buffer or File'),

Depending on the use case, the user might obviously have to assert to either File or Buffer but I think that's preferable to the code simply breaking. 😅

As you can maybe tell by looking at the rest of the app, I have already tested this approach there.

astahmer commented 1 year ago

at some point I also thought of just removing the File altogether as I'm not sure this is worth including or even useful for anyone

I'm fine with both

mykeels commented 2 months ago

At the top of the default.hbs file, I added:

const File = (typeof window === "undefined" ? require("buffer").File : window.File) as typeof window.File;

which provides a File implementation for both Node and Browser environments.