sequelize-extension

1.0.3 • Public • Published

sequelize-extension

Build Status codecov GitHub license

This module provides pre-built extensions and an interface to extend sequelize models.

Installation

$ npm install --save sequelize
$ npm install --save sequelize-extension

Usage

const Sequelize = require('sequelize');
const extendSequelize = require('sequelize-extension');

const sequelize = new Sequelize(...);

// Load Models
const db = {};
fs
  .readdirSync(__dirname)
  .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
  .forEach((file) => {
    const model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });
  
// Associate Models
db.forEach((model) => {
  if (model.associate) {
    model.associate(db);
  }
});

extendSequelize(db, {
  myCustomExtension: (db, hooks, settings) => {
    const { utils } = settings;
    _.each(db, (model) => {
      if (utils.isModel(model)) {
        _.each(utils.getAssociations(model), (association) => {
          if (utils.isListAssociation(association)) {
            // do something...
          }
        });
      }
    });
  },
});

Built-in Extensions

The built-in extensions are disabled by default. In order to enable, you can call like below:

extendSequelize(db, {
  createdBy: {},
  deletedBy: {},
  updatedBy: {},
  graphql: { gts },
  tracking: { log: console.log },
});

The built-in extensions are:

Custom Extensions

Hooks

extendSequelize(db, {
  extensionName: (db, hooks, settings) => {
    hooks.beforeUpdate.push(async (instance, options) => {
      // do something
    });
  },
});

Single instance triggers:

  • beforeUpdate (instance: Model, options: Object)
  • afterUpdate (instance: Model, options: Object)
  • beforeCreate (instance: Model, options: Object)
  • afterCreate (instance: Model, options: Object)
  • beforeDestroy (instance: Model, options: Object)
  • afterDestroy (instance: Model, options: Object)

For bulk triggers, you can pull the bulked instances using utils.getBulkedInstances(model, options). It will make at maximum one call to the database and cache the result in the options.

  • beforeBulkUpdate (options: Object)
  • afterBulkUpdate (options: Object)
  • beforeBulkCreate (options: Object)
  • afterBulkCreate (options: Object)
  • beforeBulkDestroy (options: Object)
  • afterBulkDestroy (options: Object)

Package Sidebar

Install

npm i sequelize-extension

Weekly Downloads

30

Version

1.0.3

License

MIT

Unpacked Size

78.8 kB

Total Files

28

Last publish

Collaborators

  • gcmarques