1.0.0-alpha.1.0 • Published 6 years ago

@midgar/sequelize v1.0.0-alpha.1.0

Weekly downloads
1
License
MIT
Repository
-
Last release
6 years ago

In Dev don't use this

@midgar/sequelize

It a plugin for Midgar to add Sequelize to Midgar

Installation

$ npm install @midgar/sequelize --save

Service

This plugin add a service 'midgar:sequelize' The service create db connexions defined in the midgar config and load models.

Config

The db connexions is define in the midgar config. Add a "db" key a the config root.

{
  sequelize: {
    default: {
      dialect: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'user',
      password: 'password',
      database: 'midgar',
      logging: false,
      charset: 'utf8',
      collate: 'utf8_general_ci'
    }
  }
}

"default" is the connexion name. You can add multiple connexion here. The dialect options can be found on the Sequelize documentation

Connexion

A connexion is a Sequelize instance you can read Sequelize documentation to read more about this. You can get a connection with the getConnection() method on the service:

// Get midgar:sequelize service
const sequelizeService = await midgar.getService('midgar:sequelize')
// Get default sequelize connexion
const defaultConnexion = db.getConnexion('default')

Models

Create a file in the models directory (my-plugin/sequelize/models/ by default). The module return an Object whith the model and possibly a connexion. If no connection is defined, it use the default connexion.

const Sequelize = require('sequelize');

class TestModel extends Sequelize.Model {
  static init(connexion, DataTypes) {
    return super.init(
      {
        name: {type: DataTypes.STRING, allowNull: false},
        description: {type: DataTypes.TEXT, allowNull: true},
        updatedAt: {
          allowNull: false,
          type: DataTypes.DATE,
          timestamps: true,
          defaultValue: DataTypes.NOW
        },
        createdAt: {
          allowNull: false,
          type: DataTypes.DATE,
          timestamps: true,
          defaultValue: DataTypes.NOW
        }
      },
      {
        modelName: 'test',
        sequelize: connexion
      }
    );
  }
}


module.exports = {
  model: TestModel,
  connexion: 'default'
}

Get Model instance

// Get midgar:sequelize service
const sequelizeService = await midgar.getService('midgar:sequelize')
const myModel = sequelizeService.getModel('my-model')

Cli

This plugin add some cli commands to manage db version.

npx midgar db:up

Execute all db schema and data migration not already executed.

npx midgar db:up 3

Execute 3 verions in pending list

npx midgar db:status

Show database status