这是我目前的情况:
service
提供了来自数据库(typeorm)的查询功能。
controller
提供了API,最重要的是封装数据。我希望前端能收到这样的数据:
{
code:1456,
data:{
// something real data from database
}
}
所以我在controller
@Post('save')
async save(@Body() dto: User): Promise<ResponseDTO> {
// below is a interface to define the data strcture
const result: ResponseDTO = { code: null, data: null }
await this.service.save(dto).then(v => {
result.code = 1456; // custom code
result.data = { id: v.id }; // the data from service
}).catch(() => {
result.code = 500;
})
return result
}
但是我采取的方式并不好。因为我需要在每个ResponseDTO
中初始化controller
。因此,我希望interceptor
可以帮助controller
做到这一点。
我知道如何注入拦截器,但是我不知道如何在拦截器中编写代码(不是指状态代码,而是逻辑代码)。