egg-sequelize-ts 插件

egg-sequelize-ts plugin

目的 (Purpose)

能讓使用 typescript 編寫的 egg.js 項目中可以使用 sequelize方法,並同時獲得egg.js所賦予的功能。mysql

說明 (Description)

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

安裝 (Install)

$ npm i --save egg-sequelize-ts
$ yarn add egg-sequelize-ts

配置 (Config)

  • Enable plugin in config/plugin.js
  • config/plugin.js 文件中引入 egg-sequelize-ts 組件
exports.sequelize = {
    enable: true,
    package: 'egg-sequelize-ts'
}
  • Edit your own configurations in conif/config.{env}.js
    conif/config.{env}.js 中編寫 sequelize 配置
config.sequelize = {
        dialect: 'mysql',
        host: '127.0.0.1',
        port: 3306,
        database: 'database'
    };

例子 (Example)

分別以 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;
  }
}

更改內容(Major changes)

  1. 替換 index.d.ts 文件中的類型
    主要將 interface 中的Sequelize,model指向 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

  1. 替換loader.js中的內容
  • 使用('sequelize-typescript').Sequelize替換sequelize
  • filter(model) 中使用findAll 替換sequelize,由於seq-ts在執行addModels纔會有 sequelize
  • seq-ts須要手動添加modelsapp

    sequelize.addModels(models);

    瞭解詳情,請點擊commitasync

    若是對您有幫助,歡迎 star 和推薦 (✿◡‿◡)this

相關文章
相關標籤/搜索