Detalhes do pacote

egg-sequelize

eggjs32.4kMIT6.0.0

egg Sequelize plugin

egg, sequelize, egg-plugin, eggPlugin

readme (leia-me)

egg-sequelize

Sequelize plugin for Egg.js.

NOTE: This plugin just for integrate Sequelize into Egg.js, more documentation please visit http://sequelizejs.com.

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

Install

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

# Or use other database backend.
$ npm install --save pg pg-hstore # PostgreSQL
$ npm install --save tedious # MSSQL

Usage & configuration

Read the tutorials to see a full example.

  • Enable plugin in config/plugin.js
exports.sequelize = {
  enable: true,
  package: 'egg-sequelize'
}
  • Edit your own configurations in conif/config.{env}.js
exports.sequelize = {
  dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
  database: 'test',
  host: 'localhost',
  port: 3306,
  username: 'root',
  password: '',
  // delegate: 'myModel', // load all models to `app[delegate]` and `ctx[delegate]`, default to `model`
  // baseDir: 'my_model', // load all files in `app/${baseDir}` as models, default to `model`
  // exclude: 'index.js', // ignore `app/${baseDir}/index.js` when load models, support glob and array
  // more sequelize options
};

You can also use the connection uri to configure the connection:

exports.sequelize = {
  dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
  connectionUri: 'mysql://root:@127.0.0.1:3306/test',
  // delegate: 'myModel', // load all models to `app[delegate]` and `ctx[delegate]`, default to `model`
  // baseDir: 'my_model', // load all files in `app/${baseDir}` as models, default to `model`
  // exclude: 'index.js', // ignore `app/${baseDir}/index.js` when load models, support glob and array
  // more sequelize options
};

egg-sequelize has a default sequelize options below

{
    delegate: 'model',
    baseDir: 'model',
    logging(...args) {
      // if benchmark enabled, log used
      const used = typeof args[1] === 'number' ? `[${args[1]}ms]` : '';
      app.logger.info('[egg-sequelize]%s %s', used, args[0]);
    },
    host: 'localhost',
    port: 3306,
    username: 'root',
    benchmark: true,
    define: {
      freezeTableName: false,
      underscored: true,
    },
  };

More documents please refer to Sequelize.js

Model files

Please put models under app/model dir by default.

Conventions

model file class name
user.js app.model.User
person.js app.model.Person
user_group.js app.model.UserGroup
user/profile.js app.model.User.Profile
  • Tables always has timestamp fields: created_at datetime, updated_at datetime.
  • Use underscore style column name, for example: user_id, comments_count.

Examples

Standard

Define a model first.

NOTE: options.delegate default to model, so app.model is an Instance of Sequelize, so you can use methods like: app.model.sync, app.model.query ...

// app/model/user.js

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const User = app.model.define('user', {
    login: STRING,
    name: STRING(30),
    password: STRING(32),
    age: INTEGER,
    last_sign_in_at: DATE,
    created_at: DATE,
    updated_at: DATE,
  });

  User.findByLogin = async function(login) {
    return await this.findOne({
      where: {
        login: login
      }
    });
  }

  // don't use arraw function
  User.prototype.logSignin = async function() {
    return await this.update({ last_sign_in_at: new Date() });
  }

  return User;
};

Now you can use it in your controller:

// app/controller/user.js
class UserController extends Controller {
  async index() {
    const users = await this.ctx.model.User.findAll();
    this.ctx.body = users;
  }

  async show() {
    const user = await this.ctx.model.User.findByLogin(this.ctx.params.login);
    await user.logSignin();
    this.ctx.body = user;
  }
}

Associate

Define all your associations in Model.associate() and egg-sequelize will execute it after all models loaded. See example below.

Multiple Datasources

egg-sequelize support load multiple datasources independently. You can use config.sequelize.datasources to configure and load multiple datasources.

// config/config.default.js
exports.sequelize = {
  datasources: [
    {
      delegate: 'model', // load all models to app.model and ctx.model
      baseDir: 'model', // load models from `app/model/*.js`
      database: 'biz',
      // other sequelize configurations
    },
    {
      delegate: 'admninModel', // load all models to app.adminModel and ctx.adminModel
      baseDir: 'admin_model', // load models from `app/admin_model/*.js`
      database: 'admin',
      // other sequelize configurations
    },
  ],
};

Then we can define model like this:

// app/model/user.js
module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const User = app.model.define('user', {
    login: STRING,
    name: STRING(30),
    password: STRING(32),
    age: INTEGER,
    last_sign_in_at: DATE,
    created_at: DATE,
    updated_at: DATE,
  });

  return User;
};

// app/admin_model/user.js
module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const User = app.adminModel.define('user', {
    login: STRING,
    name: STRING(30),
    password: STRING(32),
    age: INTEGER,
    last_sign_in_at: DATE,
    created_at: DATE,
    updated_at: DATE,
  });

  return User;
};

If you define the same model for different datasource, the same model file will be excute twice for different database, so we can use the secound argument to get the sequelize instance:

// app/model/user.js
// if this file will load multiple times for different datasource
// we can use the secound argument to get the sequelize instance
module.exports = (app, model) => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const User = model.define('user', {
    login: STRING,
    name: STRING(30),
    password: STRING(32),
    age: INTEGER,
    last_sign_in_at: DATE,
    created_at: DATE,
    updated_at: DATE,
  });

  return User;
};

Customize Sequelize

By default, egg-sequelize will use sequelize@5, you can cusomize sequelize version by pass sequelize instance with config.sequelize.Sequelize like this:

// config/config.default.js
exports.sequelize = {
  Sequelize: require('sequelize'),
};

Full example

// app/model/post.js

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const Post = app.model.define('Post', {
    name: STRING(30),
    user_id: INTEGER,
    created_at: DATE,
    updated_at: DATE,
  });

  Post.associate = function() {
    app.model.Post.belongsTo(app.model.User, { as: 'user' });
  }

  return Post;
};
// app/controller/post.js
class PostController extends Controller {
  async index() {
    const posts = await this.ctx.model.Post.findAll({
      attributes: [ 'id', 'user_id' ],
      include: { model: this.ctx.model.User, as: 'user' },
      where: { status: 'publish' },
      order: 'id desc',
    });

    this.ctx.body = posts;
  }

  async show() {
    const post = await this.ctx.model.Post.findByPk(this.params.id);
    const user = await post.getUser();
    post.setDataValue('user', user);
    this.ctx.body = post;
  }

  async destroy() {
    const post = await this.ctx.model.Post.findByPk(this.params.id);
    await post.destroy();
    this.ctx.body = { success: true };
  }
}

Sync model to db

We strongly recommend you to use Sequelize - Migrations to create or migrate database.

This code should only be used in development.

// {app_root}/app.js
module.exports = app => {
  if (app.config.env === 'local' || app.config.env === 'unittest') {
    app.beforeStart(async () => {
      await app.model.sync({force: true});
    });
  }
};

Migration

Using sequelize-cli to help manage your database, data structures and seed data. Please read Sequelize - Migrations to learn more infomations.

Recommended example

Questions & Suggestions

Please open an issue here.

License

MIT

changelog (log de mudanças)

6.0.0 / 2020-09-16

features

others

5.2.2 / 2020-07-01

fixes

  • [665bbd6] - fix: exception when change your config.delegate to other name, you will get an TypeError (#84) (bianchui <bianchui@gmail.com>)

5.2.1 / 2019-12-25

fixes

others

5.2.0 / 2019-07-10

features

5.1.0 / 2019-06-14

features

5.0.1 / 2019-06-11

fixes

others

5.0.0 / 2019-05-10

fixes

others

4.3.1 / 2019-01-08

fixes

4.3.0 / 2019-01-07

features

others

4.2.0 / 2018-11-12

features

others

4.1.0 / 2018-08-31

features

4.0.7 / 2018-08-20

fixes

4.0.6 / 2018-08-20

fixes

4.0.5 / 2018-08-20

fixes

4.0.4 / 2018-08-17

fixes

4.0.3 / 2018-08-17

fixes

others

4.0.2 / 2018-08-14

fixes

4.0.1 / 2018-08-13

fixes

4.0.0 / 2018-08-13

features

others

3.1.5 / 2018-07-03

features

others

  • [ff79aba] - Retry 3 times on startup when database connect fail in temporary, to avoid Egg start failed. (#57) (Jason Lee <huacnlee@gmail.com>)

3.1.4 / 2018-05-02

fixes

3.1.3 / 2018-04-13

fixes

others

3.1.2 / 2018-02-27

  • fix: auto create cli folder (#41)
  • docs: fix demo code (#42)

3.1.1 / 2018-02-06

  • fix: EGG_SERVER_ENV support for seuqlieze cli (#40)
  • docs: fix db sync doc (#31)
  • docs: add README for app.model (#34)
  • docs(README): fix a typo (#33)

3.1.0 / 2017-08-03

  • deps: update dependencies (#26)
  • refactor: rewrite cli script with plain js instead of Shell to support multi-platform. (#25)
  • docs: add a migration example for show up use co.wrap. (#24)
  • docs: fix migration url (#22)
  • docs: update history (#21)

3.0.1 / 2017-06-19

  • fix: init associate should after load of models (#20)

3.0.0 / 2017-06-19

  • feat: Upgrade Sequelize V4. (#18)
  • docs: add sync docs (#17)
  • docs(readme): fix the full example with association (#16)

2.1.4 / 2017-05-11

  • fix(migration): always use production config (#14)

2.1.3 / 2017-05-11

  • fix: Migration load config.seuqelize for function type config support.

2.1.2 / 2017-05-11

  • fix: egg-sequelize bin to find correct sequelize-cli path in node_modules.

2.1.1 / 2017-05-10

  • feat: add egg-sequelize bin for Sequelize migrations support. (#11)

2.0.2 / 2017-04-27

  • fix: ignore non Sequelize files in app/model path for Model loader. (#10)
  • docs: add Suggestions and License (#8)
  • feat: use underscore style column name as default (#7)
  • docs: add info about how to enable sequelize plugin (#6)

2.0.1 / 2017-03-14

  • fix: Allow all of Sequelize options in config.sequelize (#5)

2.0.0 / 2017-03-13

  • feat: [BREAKING_CHANGE] Update default Sequelize configs (#4)

1.0.0 / 2017-02-19

  • chore: complete unittest (#2)
  • feat: use loader API to load models (#3)