hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.64k stars 65 forks source link

[V1] global catch-all success route #211

Closed raphaelbadia closed 11 months ago

raphaelbadia commented 2 years ago

Hello, just had an idea for V1, inspired by nestjs.

In Nest they define controller functions like so :

import { Controller, Get } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string { // <---------- typed here
    return 'This action returns all cats';      // <-------- type-checked here
  }
}

Similarly to this trick : https://github.com/hoangvvo/next-connect/issues/201#issuecomment-1179556318 allowing us to catch all errors, I think it would be interesting to be all to add an onSuccess or onEnd to the handler that would run after a get/post/etc to improve the type checking.

// in the nc.ts
{
            onError: (err, req, res) => {
                res.status(400).send('failed');
            },
            onNoMatch: (req, res) => {
                res.status(404).end('Page is not found');
            },
                        onSuccess: (result, req, res) => {
                                res.status(200).json(result);
                        }
        }

type MyDTO = { text: string };

// in /pages/api/test.ts
const router = nc()
    .use(async function middleAsync(req, res, next) {
        await next();
    })
    .use(function midlesync(req, res, next) {
        return next();
    })
    .get(async function widget(req, res, next): Promise<MyDTO> {
        return {text: 'a string'}; // valid
    });

Do you think it could be an interesting addition to next-connect ?

hoangvvo commented 2 years ago

Yeah, I think it would be a good addition. Would you be willing to add a PR?

raphaelbadia commented 11 months ago

Sorry for not answering, I moved on different project, so I'll close this 🙏