Skip to content

bjrmatos/sequelize-auto-import

Repository files navigation

sequelize-auto-import

NPM VersionLicenseBuild Status

Import sequelize models automagically

This module let you import sequelize models defined in a directory and help you define each model with metadata generated based on directory structure.

Installation

npm install sequelize-auto-import

Usage

Based on a directory like this:

/path/to/models
├── Item.js
├── Service.js
├── accounts
│   └── Person.js
├── base
│   ├── Animal.js
│   └── Contact.js
└── index.js

Model definitions inside *.js files can be something like this:

module.exports = function(sequelize, DataTypes, meta) {
  // using the meta object to help us define the model
  return sequelize.define(meta.modelName, {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true
    },
    name: {
      type: DataTypes.STRING(250),
      allowNull: true
    }
  }, {
    timestamps: false,
    freezeTableName: true,
    tableName: meta.tableName,
    schema: meta.schema
  });
};

As you can see we are using the meta object generated by sequelize-auto-import to help us define the model, of course you can choose to not use these values and put what you want.

The meta object will have the following properties based on the location of the model inside the directory:

{
  schema: string?, // value to use in the `schema` option of `sequelize.define`
  schemaName: string, // the schema name of the model for your convenience
  modelName: string, // value to use as the model name of `sequelize.define`
  tableName: string, // value to use as the `tableName` option of `sequelize.define`
  completeTableName: string, // the result of `schemaName` + `separator` + `tableName` for your convenience
  separator: string // the separator that we use for your convenience
}

For example for the Item.js model the values of meta will be:

{
  schema: undefined,
  schemaName: '',
  modelName: 'Item',
  tableName: 'item',
  completeTableName: 'item',
  separator: '.'
}

and for the accounts/Person.js model:

{
  schema: 'accounts',
  schemaName: 'accounts',
  modelName: 'accounts.Person',
  tableName: 'person',
  completeTableName: 'accounts.person',
  separator: '.'
}

you can customize how the tableName is generated, see options.

With the models defined we can import all the models inside /path/to/models directory and its subdirectories using the following in index.js:

var Sequelize = require('sequelize');

var sequelize = new Sequelize('test', 'test', 'test', {
  dialect: 'mysql',
  host: 'localhost',
  port: 3306
});

// you can pass options, see bellow for details
var models = require('sequelize-auto-import')(sequelize, '/path/to/models');

// export all the models for your convenience
module.exports = models;

Now you can access the models in this way:

models.Item
models.Service
models.accounts.Person
models.base.Animal
models.base.Contact

Note that sequelize-auto-import will recursively search for js files inside the specified directory.

Optionally if your models have a associate method sequelize-auto-import will call it passing all the loaded models as a parameter, in that method you can define relations between your models if you want.

Multi-Tenancy Support (Shared Database and Separate Schemas)

Also you can create a schema folder to create multiples schemas using the same models. For example:

/path/to/models
├── user.js
├── schema
   ├── product.js
   └── contact.js
└── index.js

And with the following configuration you can indicate the schemas:

var models = require('sequelize-auto-import')(sequelize, '/path/to/models', {
   schemas: ['company1', 'company2', 'company3']
});

And access the models in this way:

models.user
models.company1.product
models.company1.contact
models.company2.product
models.company2.contact
models.company3.product
models.company3.contact

API

There is only one function exported with the following parameters:

  • sequelizeInstace A sequelize instance generated by your app
  • pathToModels The path where your models are located, if no specified default to current directory
  • options An options object, see bellow for all the available options

Options

  • recursive: boolean Whether to search inside all subdirectories or only one level, defaults to true

  • associate: boolean When true the associate method in models will be call it when found, defaults to true

  • tableNameFormat: string | function This option specifies how the tableName for the model will be generated, when a string is passed one of the established formats will be used:

    • snakeCase A model like CustomModel.js will have custom_model as tableName

    if a function is passed you can generate the tableName as you want, for example for a model like CustomModel.js and with a function like this the tableName will be custommodel:

tableNameFormat: function(modelName) {
  // modelName === 'CustomModel'
  return modelName.toLowerCase();
}

(for now we only support snakeCase as one of the available formats, open a PR if you want other formats)

  • exclude: Array A list of files to ignore when importing

  • schemas: Array A list of schema names to append in all models inside the schema folder (Multi-Tenancy Support)

Collaborators

License

See license