【发布时间】:2021-04-05 00:48:20
【问题描述】:
我有一个模型类和 2 个从模型扩展而来的子类,如下所示:
基础模型模块:
/**
*
* Provider: Model
* @module providers/core/utils/model
*
* @description provides an easy to handle sequelize model
*
*/
import { Model as SequelizeModel, InitOptions, ModelAttributes } from 'sequelize'
import sequelize from '@core/libs/sequelize'
export default
/**
*
* @class Model @extends SequelizeModel
* @description provides a more simply layer to use models
*
*/
class Model extends SequelizeModel {
/**
* @default options
*/
public static options: InitOptions = {
sequelize,
timestamps: true
}
/**
* @custom options
*/
public static $options: object = {}
/**
* @model definition
*/
public static attributes: ModelAttributes = {}
/**
* @init the model
*/
public static init (): SequelizeModel { // instead of return SequelizeModel I need to return the class who calls itself... (this)
// here just call init and not return yet
return super.init.call( this, this.attributes, {
...this.options,
...this.$options
})
// and add here return this
}
}
;
从模型扩展的类:
/**
*
* Model: User
* @module app/models/user
*
* @description basic user model
*
*/
import { Model } from '@bananasplit-js' // this is the Model above
import { DataTypes, ModelAttributes } from 'sequelize'
class User extends Model {
/**
* @fields
*/
public id!: number
public name!: string
public lastname!: string
public email!: string
public password!: string
/**
* @model
*/
public static attributes: ModelAttributes = {
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
lastname: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}
/**
* @options
*/
public static $options: object = {
timestamps: true
}
}
export default User.init() // need to return User class (for static methods usage)
// the same with product model
class Product extends Model {
... // same as User model but for products
}
Product.init() // need to return Product class
我想避免两行:
User.init()
export default User
把它变成一个:
export default User.init()
所以,我需要在从 Model 扩展的类中调用 User.init() 或 Product.init() 或 AnyClass.init() 时,返回的类型是调用 init 方法的类的类型:User|Product|AnyClass
值得一提的是,我的 Model 类也是从 Sequelize Model 类扩展而来的,它使用静态方法。
所以在我的控制器中,我使用这样的用户模型:
const users = User.findAll() // a list of all users
你可以让工作空间从 gitpod 运行:
https://gitpod.io/#snapshot/0a676aff-fdf2-4585-b349-53516d0c677e
运行服务器:yarn dev(url 路径:/test-seeder)这是可选的
运行测试(如果一切正常应该通过):yarn test setup
我需要做这些改变
【问题讨论】: