用typescript编写egg app时,如何正确使用egg-sequelize插件?
当我引入新的plugin egg-sequelize后,如何告诉ts编译器Application interface里面有个model属性呢?我在plugin.ts中激活了插件,在config.local.ts中添加了数据库连接信息,但是当我在app/model
中添加新的model定义时,编译器无法找到app.model
和app.Sequelize
,我的model文件是这样写的:
import { Application } from 'egg';
export default (app: Application) => {
const { STRING, INTEGER, DATE, DECIMAL } = app.Sequelize;
const Food = app.model.define(...);
...
}
egg-sequelize已经有ts定义了(index.d.ts),我该怎样做才能正常使用app.model
和 app.Sequelize
呢?
1 回复
定义的model有问题,model应该和controller,service那样有属性的,
declare module 'egg' {
interface Application {
Sequelize: SequelizeStatic,
model: Sequelize & IModel
}
interface Context {
model: IModel
}
interface IModel{
user:UserModel
}
// model.ts
// 结构
export interface UserObject extends BaseObject {
account: string,
userName?: string,
password?: string
}
// 实例
export interface UserInstance extends Instance<UserObject>, UserObject {
}
// 模型
export interface UserModel extends Model<UserInstance, UserObject> {
// 关联模型没提示,要加些setXXX,getXXX之类的
}
基本可以解决egg-sequelize大部分问题,就是麻烦的要死