能讓使用 typescript
編寫的 egg.js 項目中可以使用 sequelize方法,並同時獲得egg.js所賦予的功能。mysql
this plugin use sequelize-typescript
replace with sequelize
in egg.js
. at the same time, make sure of usergit
插件只是將 egg-sequelize
中的 sequelize 替換爲 sequelize-typescript, 同時保證用戶在 egg.js 建立的項目中使用 egg-sequelize
的方法儘可能一致,在使用時的不一樣,我將下面一一闡述。 其餘內容部分請查看 egg-sequelize。
此插件已在生產項目中獲得實踐。github
$ npm i --save egg-sequelize-ts $ yarn add egg-sequelize-ts
config/plugin.js
config/plugin.js
文件中引入 egg-sequelize-ts
組件exports.sequelize = { enable: true, package: 'egg-sequelize-ts' }
conif/config.{env}.js
conif/config.{env}.js
中編寫 sequelize 配置config.sequelize = { dialect: 'mysql', host: '127.0.0.1', port: 3306, database: 'database' };
分別以 model/user.js 和 service/user.js 舉例說明sql
note 注意咱們都是從
sequelize-typescript
中導出類名,方法,屬性等。typescript
// app/model/user.js /** * @desc 用戶表 */ import { AutoIncrement, Column, DataType, Model, PrimaryKey, Table } from 'sequelize-typescript'; @Table({ modelName: 'user' }) export class User extends Model<User> { @PrimaryKey @AutoIncrement @Column({ type: DataType.INTEGER(11), comment: '用戶ID', comment: 'user id' }) id: number; @Column({ comment: '用戶姓名', }) name: string; @Column({ comment: '用戶郵箱' }) email: string; @Column({ comment: '用戶手機號碼' }) phone: string; @Column({ field: 'created_at' }) createdAt: Date; @Column({ field: 'updated_at' }) updatedAt: Date; }; export default () => User;
// app/service/user.js import { Service } from 'egg'; import { Sequelize } from 'sequelize-typescript'; class UserService extends Service { async index() { const { or } = Sequelize.Op; const users = await this.ctx.model.User.findOne({ where: { [or]: [ { name, phone }, { id } ] } }); this.ctx.body = users; } }
index.d.ts
文件中的類型sequelize-typescript
.for example:npm
- import * as sequelize from "sequelize"; + import { Sequelize, ISequelizeValidationOnlyConfig } from 'sequelize-typescript'; declare module 'egg' { + // 便於egg 將方法掛載到IModel上 + interface IModel extends Sequelize { } interface Application { - Sequelize: sequelize.SequelizeStatic; - model: sequelize.Sequelize; + Sequelize: Sequelize; + model: IModel; } }
瞭解詳情,請點擊commitbash
loader.js
中的內容filter(model)
中使用findAll 替換sequelize,由於seq-ts在執行addModels纔會有 sequelizeseq-ts須要手動添加modelsapp
sequelize.addModels(models);
瞭解詳情,請點擊commitasync
若是對您有幫助,歡迎 star 和推薦 (✿◡‿◡)this