instantcommerce / next-api-decorators

Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
https://next-api-decorators.vercel.app
MIT License
409 stars 28 forks source link

Not working on NextJS app router #614

Open thienthanit04 opened 1 year ago

thienthanit04 commented 1 year ago

I'm using NextJS 13.3.4 for app router and trying to apply this package to my project. But I got this bellow exception.

SuperstrongBE commented 8 months ago

Exact same error for me It's seems that the new way Next js structure the API in route and a set of named function (get, post, ... ) doesn't fit the way Next-API-Decorator createHandler works

SuperstrongBE commented 8 months ago

Testing some workaround but lot of classes use NextApiRequest and NextApiResponse instead of the new NextRequest or NextResponse. Also createHandler should return a set of decorated function or allow more simple process like

import {Body,Post} from 'next-api-decorators'
import { ValidateIdentityDto } from "../../dto/validate-identity.dto";

class IdentityController {

  @Post()
  async validateIdentity(@Body() body: ValidateIdentityDto) {
    console.log(body)
    return Response.json({val:"identity verified",body})
  }
}
// Create the controller 
const controller = new IdentityController();

export async function POST(req: Request, res: Response): Promise<Response> {
  const body = await req.json()
  //Use controller function
  return controller.validateIdentity(body) 
}

The provided code above not working, the @Post decorator throw an error.

Nothing is really usable in app router. I'm a huge fan of NestJS decorator, allow it in NextJS is game changer, but it needs app router support. @ggurkal or @leeuwis any roadmap to support app router ? I've forked the repo, but some part of the code is outside of my skills, maybe team can helps for app router implementation :)

SuperstrongBE commented 7 months ago

Hello ! I just posted a research around decorator around the new Route handler in NextJS App router to find a possible solution outside this repo and potentially fork and update with the final solution https://discord.com/channels/752553802359505017/1007476603422527558/threads/1176167694735786096

I also create a gist to make my own research around decorator https://gist.github.com/SuperstrongBE/2d4e6d1aac89797270745f22c9ba047b Feel free to reach me if you have advices / tips

g-monroe commented 5 months ago

I was also working on this, as having a robust easy routing through classes and decorators is a must for me. So even here my attempt with reference to @SuperstrongBE inspirations. Still working on it, but got path routing down, with args being passed down. https://gist.github.com/g-monroe/307005780ec0c63854598ef9bf3771d0