I want to implement an endpoint that inserts a record into a history table. If there is no user_id
associated with the history (i.e., it is the first time a history is inserted), it should return status code 201. Otherwise, it should return status code 200.
This is the only method I can think of to achieve this.
service
async putHistory(/* ... */): Promise<{ isNew: boolean; result: PutHistory }> {
// ...
return {
isNew, // identifier for determining the status code
result: {
// ...
},
};
}
controller
@Put()
@HttpCode(200)
@HttpCode(201)
putHistory(@Res() res: Response): Response<any, Record<string, any>> {
const { isNew, result } = this.historyService.putHistory(/* ... */);
return res.status(isNew ? HttpStatus.CREATED : HttpStatus.OK).send(result);
}
However, with this method, Express Response
type becomes the return type of controller, making the code look unsettling. Is there a more elegant way to write this?