首页 > 解决方案 > 有没有办法从猫鼬返回数据?打字稿,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();
}

或使用的一些好的做法?

标签: typescriptmongoosenestjs

解决方案


以下是代码的一些问题

  1. 不要awaitthen(). await将语句包装在then().
  2. 您不需要自己编写 HTTP 错误。NestJS 提供了很多默认的
  3. 如果您需要编写自己的错误,请使用异常过滤器来捕获它们并为自定义错误编写自己的逻辑。
  4. 不要注射@Req@Res无处不在。使用DTO。它是救生员。
  5. 始终尝试在 DTO 或接口中返回响应。
  6. 尝试处理相关的错误。不在控制器中(不总是)

如何在 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
}

推荐阅读