1.0.5 • Published 2 years ago

midway3-sequelize v1.0.5

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

midway3-sequelize

###只适用于midway3.x版本

使用方法

###安装

// yarn
yarn add midway3-sequelize

// npm
npm install midway3-sequelize
// 使用mysql  注意mysql版本不能低于5.7 
yarn add mysql2 

configuration.ts 文件引入组件

import * as sequelize from 'midway3-sequelize';
@Configuration({
  imports: [
    koa,
    sequelize,
  ],
  importConfigs: [join(__dirname, './config')],
})

添加配置项 config.local.ts

// 和sequelize参数一样一样的,自行修改
export const sequelize = {
  options: {
    dialect: 'mysql',
    host: '127.0.0.1',
    port: '3306',
    database: 'fang_test',
    username: 'root',
    password: 'root',
    timezone: '+08:00',
    define: {
      timestamps: true,
      paranoid: true,
      charset: 'utf8',
      underscored: true,
    },
    dialectOptions: {
      dateStrings: true,
      typeCast: (field: any, next: () => void) => {
        if (field.type === 'DATETIME') {
          return field.string();
        }
        return next();
      },
    },
  },
  sync: false,
};

创建model文件 参考下就行了 🤣

后面会更新下model文件生成工具 适用于此版本(写代码,能少些就不多写,写的越多bug越多🤓)

import { Model, Column } from 'sequelize-typescript';
import { BaseTable, STRING } from 'midway3-sequelize';

// #region enum
// #endregion

@BaseTable({
  tableName: 'user',
})
export class UserModel extends Model {
  /**
   * 密码
   */
  @Column({ comment: '密码', type: STRING })
  password: string;

  /**
   * 用户名
   */
  @Column({ comment: '用户名', type: STRING })
  username: string;
}

// 常量生成
export class ConstUser { 
  /**
   * password
   */
  static readonly PASSWORD: string = 'password';
  /**
   * username
   */
  static readonly USERNAME: string = 'username';
}

service 使用 值得你参考😉

import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '../core/base/base.service';
import { GetUser } from '../core/dto/user';
import { UserModel, ConsUser } from '../core/models/user.model';
import { DBContext, Op, literal, Transaction } from 'midway3-sequelize'

@Provide()
export class UserService extends BaseService {
  @Inject()
  dBContext: DBContext; // 获取 sequelize 实例化对象
  async getUser(options: GetUser) {
    // 事物 隔离级别自己设置就完了
    const t: Transaction = await this.dBContext.sequelize.transaction(); 
    try {
      await UserModel.create({[ConstUser.USERNAME]: 'lisi'})
      await UserModel.update(
        {[ConstUser.USERNAME]: 'zhangsan'}, 
        {where: {[ConstSysUser.USERNAME]: 'lisi'}, transaction: t})
      await t.commit()
    } catch (error) {
      console.log(error)
      await t.rollback()
    }
    
    const res = await UserModel.findOne({
      where: { [ConstUser.ID]: options.uid },
    });
    return { res }
  }
}
1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago