next-connect icon indicating copy to clipboard operation
next-connect copied to clipboard

[V1] global catch-all success route

Open raphaelbadia opened this issue 1 year ago • 1 comments

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 ?

raphaelbadia avatar Aug 23 '22 12:08 raphaelbadia

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

hoangvvo avatar Aug 31 '22 19:08 hoangvvo

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

raphaelbadia avatar Oct 11 '23 09:10 raphaelbadia