typescript - 有没有办法从猫鼬返回数据?打字稿,NestJS
问题描述
我正在使用nestjs 和猫鼬。是否有正确的方法来返回数据或简化此代码?特别是让响应= ....
宠物控制器.ts
.
.
//getPets
@Get('read')
async getPets(@Req() _req: Request, @Res() _res: Response) {
let response: HttpResponse = await this.petService.getAll()
.then(result => {
return {
code: HttpStatus.OK,
ok: true,
message: result,
}
}).catch(err => {
return {
code: HttpStatus.INTERNAL_SERVER_ERROR,
ok: true,
message: err,
}
});
return _res.status(response.code).json(response);
}
宠物服务.ts
//READ ALL
async getAll(): Promise<PetInterface[]> {
return await this.petsModel.find();
}
或使用的一些好的做法?
解决方案
以下是代码的一些问题
- 不要
await
与then()
.await
将语句包装在then()
. - 您不需要自己编写 HTTP 错误。NestJS 提供了很多默认的。
- 如果您需要编写自己的错误,请使用异常过滤器来捕获它们并为自定义错误编写自己的逻辑。
- 不要注射
@Req
和@Res
无处不在。使用DTO。它是救生员。 - 始终尝试在 DTO 或接口中返回响应。
- 尝试处理相关的错误。不在控制器中(不总是)
如何在 NestJS 方式中做到这一点:
宠物控制器.ts
//getPets
@Get('read')
public async getPets() {
return await this.petService.getAll();
}
宠物服务.ts
//READ ALL
public async getAll(): Promise<PetResponseDTO[]> {
try{
const petsQueryResult = await this.petsModel.find();
return PetResponseDTO.listOfPetsFromQueryResult(petsQueryResult);
}catch (e){
//Whatever you want to do with the error.
//...
//Imported from @nestjs/common
throw new BadRequestException('<Reason>');
// OR
throw new InternalServerErrorException();
}
}
宠物响应.dto
export class PetResponseDTO{
public static listOfPetsFromQueryResult(petsQueryResult:<query result type>[]): PetResponseDTO[]{
const listOfAllPets = [];
for(const pet of petsQueryResult){
listOfAllPets.push(new PetResponseDTO(id,name,petType));
}
return listOfAllPets;
}
constructor(id:string,name:string,petType:string){
this.id = id;
this.petType = petType;
this.name = name;
}
id: string;
name: string;
petType: string;
//....Whatever fields you want
}
推荐阅读
- python - 防止在 python 中重复预订(日程检查器)
- php - ImageMagick quantizeImage 在新版本上慢 100 倍
- reactjs - 谷歌地图 API 接收到的反应组件更新数据中的 setState 问题
- wordpress - 如何在 wordpress 中使用 tax_query 显示自定义循环中使用的术语名称
- python - 在 keras 模型中输入时,我的输入 np 数组变成不同的形状
- microsoft-edge - 使用 launchWebAuthFlow api 发布扩展
- android - 从 google play 控制台派生的 apk 无法正常工作,但原始 apk 工作正常
- google-apps-script - Google App Script如何将公式设置为Google表格单元格
- php - 删除文本并仅返回 PHP 中的第一个链接
- python - 使用 selenium 选择具有重复类名的元素