h3 icon indicating copy to clipboard operation
h3 copied to clipboard

Add `readValidatedMultipartFormData`

Open genu opened this issue 1 year ago • 0 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

  • [X] Would you be willing to help implement this feature?

genu avatar Mar 15 '24 16:03 genu