Node.js 和sequelize-typescript - 数据访问对象和业务对象

标签 node.js typescript orm sequelize.js sequelize-typescript

我正在使用sequelize-typescript在我的 Node.js 服务中

我有映射到类别表的Category

import { Model, Table, Column } from "sequelize-typescript";

@Table
export class Category extends Model<Category>{

    @Column
    name: string
}

我还有CategoryControllerCategoryService

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/

相关文章:

Angular2 No provider for AngularFireDatabase 注入(inject)错误

java - ORMLite 异步操作

javascript - Node.js、Cygwin 和 Socket.io 走进一家酒吧……Node.js 抛出 ENOBUFS,所有人都死了

node.js - 如何在 Judo 中设置 maxBuffer

javascript - Node.js 中的异步 http.get 调用(Learyounode 练习)

javascript - 如何模拟正在测试的服务调用的函数的实现?

Angular 2 CanActivate 不起作用

java - Hibernate 条件接受 %% 值

php - 如何在 Eloquent Laravel 中使用名称查找条目?

javascript - 为 mongodb REST API 编写通用查询函数