fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
5.6k stars 169 forks source link

Questions on how to proceed #646

Closed devcaeg closed 3 weeks ago

devcaeg commented 3 weeks ago

Hello,

I am creating a schema which has a field that can be a string or a blob and using transform from Valibot I convert them into a file, the problem is that if in the same schema I want to continue applying validators to file, Valibot is not allowing me to do it.

const schema = pipe(
  union([string(), blob()]),
  transform((input) =>
    typeof input === "string"
      ? base64ToFile(input, "test")
      : new File([input], "test")
  ),
  mimeType(["image/jpeg"]) <-- Here I get a `TypeScript` error
);

Error: Type MimeTypeAction<Blob, ["image/jpeg"], undefined> is not assignable to type BaseValidation<File, unknown, BaseIssue<unknown>>

Is there any other way this can be done?

fabian-hiller commented 3 weeks ago

Is it possible that base64ToFile is causing the problem? The following scheme works in our playground:

import * as v from 'valibot';

const Schema = v.pipe(
  v.union([v.string(), v.blob()]),
  v.transform((input) =>
    typeof input === "string"
      ? new File([input], "test")
      : input
  ),
  v.mimeType(["image/jpeg"])
);

Personally, I would write this schema differently if the transformation and validation is not necessary in every case. Here is an example:

const Schema = v.union([
  v.pipe(
    v.string(),
    v.transform((input) => new File([input], 'image.jpg'))
  ),
  v.pipe(v.blob(), v.mimeType(['image/jpeg'])),
]);
devcaeg commented 3 weeks ago

Thank you very much for your response. I have come to the conclusion that the error is caused by Bun since they are somehow interfering and generating discrepancies between the Blob, and File types.

devcaeg commented 3 weeks ago

I will close the problem in Valibot given that it is a problem with the types in Bun

fabian-hiller commented 3 weeks ago

You can try to replace blob() with instance(File).