unjs / h3

⚡️ Minimal H(TTP) framework built for high performance and portability

Home Page:https://h3.unjs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add `readValidatedMultipartFormData`

genu opened this issue · comments

Describe the feature

Its a good pattern for multipart data to include both data and files. I implemented this pattern internally, but I think it would offer a good out of the box convenience.

The idea is that given this data object:

{
    "name": "John doe",
    "profileImage": File
}

To send it to the backend, we must send it using FormData like this:

{
     "data": <JSON.stringify({
     {
        "name": "John doe",
        "profileImage": "file_0"
     }
     })>,
     "file_0": <binary>
}

In a route, we would do:

const data = await readValidatedMultipartFormData(event, MySchema.parse);

The opinionated aspects:

  • the frontend would need to handle structuring the payload. In my implementation, I do a recursive search of the data and replace all File objects with a reference (e.g. file_x) and append the file at the end of the FormData. Then I stringify the payload into data
  • On the backend, I essentially do the reverse to rebuild the original data structure, and then pass it through the validator.

Let me know your thoughts.

Additional information

  • Would you be willing to help implement this feature?

Thanks for suggestion. In upcoming h3 v2, readBody and readValidatedBody also parse application/x-www-form-urlencoded and as a result allow validating object.