souche / egg-typescript-sequelize

MIT License
5 stars 2 forks source link

egg-typescript-sequelize

NPM version build status Test coverage David deps Known Vulnerabilities npm download

sequelize-typescript for Egg.js, more documentation please visit sequelize-typescript.

Install

$ npm i egg-typescript-sequelize --save
$ npm install --save mysql2 # For both mysql and mariadb dialects

Features

Usage & Configuration

// {app_root}/config/plugin.js
exports.tsSequelize = {
  enable: true,
  package: 'egg-typescript-sequelize',
};
// {app_root}/tshelper.js
module.exports = {
  watchDirs: {
    // blue-windy-sequelize 配置
    model: require('egg-typescript-sequelize/tshelper'),
  }
}
// {app_root}/config/config.default.js
exports.sequelize = {
  clients: {
    test: {
      database: 'test',
      dialect: 'mysql',
      host: 'localhost',
      port: '3306',
      username: 'root',
      password: '',
      // Sync all defined models to the DB, default false.
      // isAutoSync: true,
    },
    test2: {
      database: 'test2',
      dialect: 'mysql',
      host: 'localhost',
      port: '3306',
      username: 'root',
      password: '',
      // Sync all defined models to the DB, default false.
      // isAutoSync: true,
    },
  },
  // default config, dbconfig = Object.assign({}, default, dbconfig);
  default: {

  },
  // mount to app, default true
  // app: true,
  // mount to agent, default false
  // agent: true,
};

see config/config.default.js for more detail.

Example

Define models:

// {app_root}/model/test/uset.ts
import { Table, Column, Model, HasMany } from 'sequelize-typescript';
import post from './post';

@Table
export default class user extends Model<user> {
  @Column({
    primaryKey: true,
    autoIncrement: true,
  })
  id: number

  @Column
  name: string

  @Column({
    defaultValue: '',
  })
  nickName: string

  @HasMany(() => post)
  post: post[];
}

// {app_root}/model/test/post.ts

import { Table, Column, Model, ForeignKey } from 'sequelize-typescript';
import user from './user';

@Table({
  timestamps: true,
})
export default class post extends Model<post> {
  @Column({
    primaryKey: true,
    autoIncrement: true,
  })
  id: number

  @Column
  name: string

  @ForeignKey(() => user)
  @Column
  user_id: number
}

Now you can use it in your controller:

// app/controller/user.js
import { Controller } from 'egg';

export default class UserController extends Controller {
  async jpush() {
    const result = await this.app.model.test.user.findOne();
    // association query
    // const result = await app.model.test.user.findOne({ include: [ app.model.test.post ], where: { nick_name: 'xl' } });
    this.ctx.body = result;
  }
}

more documentation please visit sequelize-typescript.

Questions & Suggestions

Please open an issue here.

License

MIT