node.js - 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)
并使用它吗?
解决方案
尝试这个:
const cat: CreateCatDto = { name: 'Miau', breed: 'some' };
推荐阅读
- javascript - javascript排序没有多个条目
- java - 我的应用程序在 Android 8.0 版本上失败原因:java.lang.IndexOutOfBoundsException:
- excel - 修复 MS Excel 中针对目标移动的公式
- wpf - 使用 MVVM 模型层中的 WPF 文本框内容
- java - 如何在 Java 中为 Android 项目制作 Text Bold 的特定部分?
- .htaccess - 重写的 URL 以一种奇怪的方式工作
- swift - Alamofire + Gloss:嵌套 JSON 数组不起作用
- python-3.x - Plotly:使用 pandas 数据框中的行名创建表
- node.js - NodeJS 与 MongoDB 的连接(在 AWS C9 上)返回未定义的 db 对象
- r - 仅保留数据框中的小数