【问题标题】:is there a way to return data from mongoose? Typescript, NestJS有没有办法从猫鼬返回数据?打字稿,NestJS
【发布时间】:2021-08-04 07:06:33
【问题描述】:

我正在使用nestjs 和猫鼬。是否有正确的方法来返回数据或简化此代码?尤其是让 response = ....

pets.controller.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);
}

pets.service.ts

//READ ALL
async getAll(): Promise<PetInterface[]> {

    return await this.petsModel.find();
}

或使用了一些好的做法?

【问题讨论】:

    标签: typescript mongoose nestjs


    【解决方案1】:

    这里有一些代码问题

    1. 不要将awaitthen() 一起使用。 await 将语句包装在 then() 中。
    2. 您不需要自己编写 HTTP 错误。 NestJS 提供了大量的default ones
    3. 如果您需要编写自己的错误,请使用exception filters 捕获它们并编写自己的 自定义错误的逻辑。
    4. 不要到处注入@Req@Res。使用DTOs。它是救生员。
    5. 始终尝试在 DTO 或接口中返回响应。
    6. 尝试处理相关的错误。不在控制器中(并非总是)

    如何在 NestJS 方式中做到这一点:

    pets.controller.ts

    //getPets
    @Get('read')
    public async getPets() {
        return await this.petService.getAll();
    }
    

    pets.service.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();
            }
    }
    

    pet.response.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
    }
    

    【讨论】:

    • 当我想发送这样的回复时会发生什么?在本例中为 JSON({ 代码:HttpStatus.OK,ok:true,message:result,})。我需要使用 Res。在我的 Post 请求中也有 Req。不仅仅是身体
    • 你可以使用interceptors作为路由。您将从execution context 获得整个响应和请求对象。您可以检查响应,映射自定义数据格式并将其发回。
    【解决方案2】:

    另外,扩展关于 Mongo 本身的 SPS 答案。

    如果您为 API 响应返回文档,则不需要 Mongoose 文档本身。它们的精益版本会很好,而且重量要轻得多。因此,将.lean() 添加到您的查询中,例如await this.petsModel.find().lean()(或将其作为{ query: option } 传递)。单个文档的接口类型为LeanDocument&lt;Doctype&gt;

    第二件事是:不要在一个查询中返回所有文档。可以用于学习目的,但不能用于生产。将limit 添加到您的查询中,使用limitskip 进行分页,或通过cursor() 流式传输数据。

    【讨论】:

    • Yap.. 这是一个很棒的优化。我完全看过了。
    猜你喜欢
    • 2022-11-22
    • 2021-02-12
    • 2021-01-05
    • 2021-09-26
    • 2016-11-14
    • 2016-02-05
    • 2020-05-11
    • 2018-07-12
    • 2013-04-10
    相关资源
    最近更新 更多