Global response function
Closed this issue · 3 comments
AnandChowdhary commented
I'm trying to implement something where I can just return the object instead of using res.json
, and would love to hear your thoughts on how it might be done.
For example, instead of this:
@Controller('api/users')
export class UserController {
@Get(':id')
private get(req: Request, res: Response) {
return res.status(OK).json({
message: 'get_called',
});
}
}
I can write this:
@Controller('api/users')
export class UserController {
@Get(':id')
private get(req: Request, res: Response) {
return {
message: 'get_called',
};
}
}
And perhaps have a global response function somewhere:
this.app.onResponse = (returned: any, req: Request, res: Response) => {
res.json(returned);
};
seanpmaxwell commented
This is certainly doable but it deviates from express more than I'd like to go. I didn't want overnight to be an abstraction of top of express.
joeykilpatrick commented
@AnandChowdhary Try the following as a wrapper:
function statusOkWithJson(method: Function): RequestHandler {
return (req: Request, res: Response): Response => {
return res.status(200).json(method(req, res));
}
}
Full example in this gist.
AnandChowdhary commented
This makes perfect sense, @joeykilpatrick.
@seanpmaxwell Do you think we can have a global wrapper? Since there's global middleware, class middleware, and function middleware, but only class wrapper and function wrapper.