Node Sequelize migrations / models can the same code be shared?

I'm new to Sequelize so please be patient.

I started a new project using Sequelize and migrations, so I got this:

Migration / 20150210104840 create-my-user.js:

"use strict";
module.exports = {
  up: function(migration, DataTypes, done) {
    migration.createTable("MyUsers", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER
      },
      first_name: {
        type: DataTypes.STRING
      },
      last_name: {
        type: DataTypes.STRING
      },
      bio: {
        type: DataTypes.TEXT
      },
      createdAt: {
        allowNull: false,
        type: DataTypes.DATE
      },
      updatedAt: {
        allowNull: false,
        type: DataTypes.DATE
      }
    }).done(done);
  },
  down: function(migration, DataTypes, done) {
    migration.dropTable("MyUsers").done(done);
  }
};

      

models / myuser.js:

"use strict";
module.exports = function(sequelize, DataTypes) {
  var MyUser = sequelize.define("MyUser", {
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    bio: DataTypes.TEXT
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });
  return MyUser;
};

      

as you can see the definition of the table on both the migration and the model file.

I am wondering if there is a way to share the code?

I mean I don't like having logic in two files if I change a field I have to update it twice.

UPDATE

after the Yan Foto example below, the other way might be cleaner.

Schemes / Users

'use strict';

module.exports = {
    name: 'users',
    definition : function(DataTypes)  {
        return {
            id: {
                type: DataTypes.INTEGER,
                autoIncrement: true,
                primaryKey: true
            },
            firstname: {
                type:DataTypes.STRING
            },
            lastname: {
                type:DataTypes.STRING
            },
            email: {
                type: DataTypes.STRING,
                unique: true
            },
            username: {
                type:DataTypes.STRING,
                unique: true
            }
        };
    }
};

      

models / users

'use strict';

var Schema = require('../schemas/users');

module.exports = function(sequelize, DataTypes) {
    return sequelize.define(
        Schema.name,
        Schema.definition(DataTypes),
        {
            freezeTableName: true ,
                instanceMethods: {
                countTasks: function() {
                        // how to implement this method ?
                }
                }
        }
    );
};

      

Migration /20150720184716-users.js

'use strict';

    var Schema = require('../schemas/users');

    module.exports = {

        up: function (queryInterface, Sequelize) {
                return queryInterface.createTable(
                Schema.name,
                Schema.definition(Sequelize)
                );
        },

        down: function (queryInterface, Sequelize) {
            return queryInterface.dropTable(Schema.name);
        }

    };

      

+1


source to share


1 answer


I was wondering if I started using sequelize and here is my solution. I define my models below:

module.exports = {
  def: function(DataTypes) {
    return {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      username: DataTypes.STRING,
      password: DataTypes.STRING,
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    }
  },
  config: {}
};

      

Where def

defines attributes, and config

is optional object options

adopted define

or migration methods . And I import them using the following code:



fs.readdirSync(__dirname + '/PATH/TO/models')
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename);
  })
  .forEach(function(file) {
    var name = file.substring(0, file.lastIndexOf(".")),
        definition = require(path.join(__dirname + '/models', file));

    sequelize['import'](name, function(sequelize, DataTypes) {
      return sequelize.define(
        name,
        definition.def(DataTypes),
        definition.config
      );
    });
  });

      

For migrations, I have a similar approach:

const path = require('path');

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.createTable(
      'users',
      require(path.join(__dirname + '/PATH/TO/models', 'user.js')).def(Sequelize)
    );
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.dropTable('users');
  }
};

      

+3


source







All Articles