首页 > 解决方案 > NestJS - 从其他服务创建业务对象

问题描述

现在我在玩 NestJS 并试图了解 NestJS 世界的最佳实践。

通过遵循官方文档,我为名为“ Cat ”的业务对象创建了 service/dto/entity/controller。

(也使用 SequelizeJS)

cat.entity.ts
@Table({
  freezeTableName: true,
})
export class Cat extends Model<Cat> {
    @AllowNull(false)
    @Column
    name: string;
    @Column
    breed: string;
}



create-cat.dto.ts
export class CreateCatDto {
    @IsString()
    readonly name: string;
    @IsString()
    readonly breed: string;
}


cat.service.ts
export class CatService {
    constructor(@Inject('CAT_REPOSITORY') private readonly CAT_REPOSITORY: typeof Cat) {}
    async create(createCatDto: CreateCatDto): Promise<Cat> {
        const cat = new Cat();
        cat.name = createCatDto.name;
        cat.breed = createCatDto.breed;

        return await cat.save();
    }
}

现在我可以向我的控制器发出 POST 请求并成功创建 Cat 对象。但是我想从其他服务创建一个“猫”,并且该create()方法只采用CreateCatDto我不能/不应该初始化的方法(它是只读的)。

我如何create(createCatDto: CreateCatDto)从其他服务呼叫?您如何使用 NestJS 处理此类要求?我应该再创建一种方法createFromEntity(cat: Cat)并使用它吗?

标签: node.jstypescriptnestjs

解决方案


尝试这个:

const cat: CreateCatDto = { name: 'Miau', breed: 'some' };

推荐阅读