skutil-sequelize

1.0.3 • Public • Published

Sequelize utils used by the author privately.

Install

yarn add skutil-sequelize

Usage

Suppose the ./models dir contains model definition files like:

// ./models/user.js

const { Model, DataTypes } = require('sequelize')

module.exports = function(sequelize) {
  class User extends Model {}
  User.init({
    username: { type: DataTypes.STRING(30), unique: 'username', allowNull: false },
    password: { type: DataTypes.STRING, allowNull: false, defaultValue: '' },
    nickname: { type: DataTypes.STRING, allowNull: false, defaultValue: 'Alice' },
    roleId: { type: DataTypes.INTEGER, allowNull: false }
  }, {
    sequelize,
    tableName: 'user',
    timestamps: true
  })
  return User
}

You can also define a dynamic model, which can be used to split the table:

// ./models/leaderboard.js

const { Model, DataTypes } = require('sequelize')

class ModelCreator {
  constructor() {
    this.isDynamic = true
    this.modelPrefix = 'LeaderBoard'
    this.tablePrefix = 'leaderboard'
  }

  createModel(sequelize, postfix) {
    postfix = postfix || ''
    const modelName = this.modelPrefix + postfix
    const tableName = this.tablePrefix + ((postfix.length > 0) ? ('_' + postfix) : '')

    class LeaderBoard extends Model {
      static associate(models) {
        models.User.hasOne(LeaderBoard, {
          sourceKey: 'id',
          foreignKey: { name: 'userId', allowNull: false },
          as: `lb_${postfix}`
        })
        LeaderBoard.belongsTo(models.User, {
          targetKey: 'id',
          foreignKey: { name: 'userId', allowNull: false },
          as: 'user'
        })
      }
    }

    LeaderBoard.init({
      score: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }
    }, {
      sequelize,
      modelName,
      tableName,
      timestamps: true
    })
    LeaderBoard.associate(sequelize.models)
    return LeaderBoard
  }
}
module.exports = new ModelCreator()

We can load all the models with this module:

const { Database } = require('skutil-sequelize')
const db = new Database()
db.init({
  dialect: 'mysql',
  host: '127.0.0.1',
  port: 3306,
  username: 'yourun',
  password: 'yourpwd',
  database: 'yourdb',
  logging: (process.env.DEBUG_DB === 'true') ? msg => console.debug(msg) : false
})
db.loadModels('./models', { root: __dirname })

const sequelize = db.sequelize
const models = sequelize.models
const { User } = models
const LeaderBoard = await db.getDynamicModel('LeaderBoard', '202211')
const records = await Leaderboard.findAll()

ChangeLog

  • 1.0.2 去除skutil依赖, README写点基本用法

Readme

Keywords

Package Sidebar

Install

npm i skutil-sequelize

Weekly Downloads

0

Version

1.0.3

License

MIT

Unpacked Size

11 kB

Total Files

7

Last publish

Collaborators

  • stayknight