我正在使用sequelize-typescript在我的 Node.js 服务中
我有映射到类别表的Category
类
import { Model, Table, Column } from "sequelize-typescript";
@Table
export class Category extends Model<Category>{
@Column
name: string
}
我还有CategoryController
和CategoryService
export class CategoryController {
...
async getAll(request: Request, response: Response) {
let categories = await this.categoryService.getCatergories();
response.json(categories)
}
}
export class CategoryService {
async getCatergories(): Promise<Category[]> {
let categories = await Category.findAll<Category>()
return categories
}
}
一切都是它应该的样子。
但是向 Controller 返回一个Category
允许它使用模型类的继承方法,例如:
export class CategoryController {
...
async getAll(request: Request, response: Response) {
let categories = await this.categoryService.getCatergories();
// Remove associated row in the database
categories[0].destroy()
response.json(categories)
}
}
我正在考虑创建一个像这样的CategoryModel
类:
export class CategoryModel {
id : number
name : string
}
并修改 CategoryService
中的所有方法以返回 CategoryModel
实例而不是 Category
并将 Category
重命名为 类别实体
处理此类问题的最佳方法是什么?
最佳答案
使用 Category
实例的 toJSON()
来获取实例的“JSON 表示”。
请参阅sequelize 文档以获取更多信息:http://docs.sequelizejs.com/class/lib/model.js~Model.html#instance-method-toJSON
此外,您可以添加一个接口(interface)来实现 toJSON()
返回值的类型安全,而不是定义另一个类:
interface ICategory {
id: number;
name: string;
}
@Table
export class Category extends Model<Category> implements ICategory{
@Column
name: string
}
使用toJSON()
:
Category.findOne(result => {
const category: ICategory = result.toJSON();
});
关于Node.js 和sequelize-typescript - 数据访问对象和业务对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45435231/