blomqma / next-rest-framework

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

Make handlers compatible with Next Server Actions #77

Closed SaadBazaz closed 11 months ago

SaadBazaz commented 11 months ago

I'm working on a project and I have an interesting proposition.

What if we could create Next APIs, and with the same functions, we could create Next Server Actions?

Benefit:

  1. The primary app (Next Frontend) can directly use the Server Actions
  2. Other users can use the API externally

Right now my setup looks something like this:

Screenshot 2023-10-15 at 18 52 37

As you can see, createProject is being repeated on both sides. If we could make the handler compatible with the REST API somehow, we could have one function for both.

I'd prefer if there was just one "handler" with does both the Server Action and can be used for the Rest API.

blomqma commented 11 months ago

I think what you're asking is generally not possible, because the API endpoints are meant to handle raw request objects, whereas server actions are just plain functions that don't care in which format the arguments are provided. However, nothing prevents you from calling your server actions from within your REST API handlers, so your Next REST Framework handlers could look something like:

...
handler: async (req) => {
  const jsonData = await req.json();
  const res = await myServerAction(jsonData);
  return NextResponse.json(res, {
    status: 200
  })
},
...

Additionally, you could abstract the example above to a single function where you could pass your server action as an argument and use that throughout your application.

SaadBazaz commented 11 months ago

That's exactly what I thought too. Ok I'll see if I can kill these two birds with one stone