blomqma / next-rest-framework

Type-safe, self-documenting APIs for Next.js
https://next-rest-framework.vercel.app
Other
134 stars 17 forks source link

FormData support in rpcRoutes #143

Closed andydam closed 5 months ago

andydam commented 5 months ago

I've created an rpcOperation that takes in FormData for uploading files and it seems to work fine when called as a Server Action (although with a type error in .input() args probably due to zod-form-data)

Example:

import { rpcOperation } from 'next-rest-framework';
import { z } from 'zod';
import { zfd } from 'zod-form-data';

export const testRpc = rpcOperation()
  .input(zfd.formData({ file: zfd.file() }))
  .outputs([{ schema: z.string() }])
  .handler((inputs: FormData) => {
    // returns file name
    return inputs.get('file').name;
  });

When using rpcRoute with App Router to access this rpcOperation outside of a Server Action fails though, with a

{
    "message": "Invalid media type."
}

response since rpcRoute only supports JSON. It would be great if multipart/form-data requests were supported, either built into the framework by passing App Router's request.formData() (https://nextjs.org/docs/app/building-your-application/routing/route-handlers#request-body-formdata) into the validator when content-type is multipart/form-data or having some way to override the JSON parsing in rpcRoute with custom handling to support multipart/form-data

blomqma commented 5 months ago

Yeah parsing form data is currently not very well supported, thanks for reporting. As Next.js docs directly recommends using zod-form-data to parse form data, I think it could be well integrated to this framework as it already highly leverages Zod, I'll look into it 👍🏻

blomqma commented 5 months ago

Hey, v6.0.0-beta.1 is now released that introduces overall better, stronly-typed form data support, also for RPC routes. There's an example on how to use form data with RPC routes now, hope this resolves your issue: https://github.com/blomqma/next-rest-framework?tab=readme-ov-file#rpc-endpoints