1

I have this module on NodeJS:

const { cloneDeep, mapValues } = require('lodash');

module.exports = function(Sequelize) {
  return new ( function(Sequelize) {
    /* Preserve this pointer into forEach callbacks scope */
    var self = this;

    this.types = {
      'string'  : Sequelize.STRING,
      'text'    : Sequelize.TEXT,
      'integer' : Sequelize.INTEGER,
      'int'     : Sequelize.INTEGER,
      'decimal' : Sequelize.DECIMAL,
      'date'    : Sequelize.DATE,
      'boolean' : Sequelize.BOOLEAN,
    };

    /* Convert the Agence model Syntax to Sequelize syntax */

    this.parse = function(model) {

      /* Convert model Agence attributes to Sequelize types attribs */
      function toSequelizeTypes(attributes) {
        return mapValues(attributes, function(attribute) {
          var attribSettings    = cloneDeep(attribute);
          attribSettings.type   = self.types[attribSettings.type];
          return attribSettings
        });
      }

      return {
        tableName: model.tableName,
        attributes : toSequelizeTypes(model.attributes),
        hooks : model.hooks || {},
        classMethods : model.classMethods || {},
        instanceMethods : model.instanceMethods || {}
      };
    };

  })(Sequelize);
};

And as you can see, the parenthesis before return new closes, and then it comes a (Sequelize) section, where it finishes and finally closes the main function for the export. What does the (Sequelize) thing do? I've never seen this kind of sintaxis before.

1 Answers1

5

This is an IIFE. It's a function created and run inline.

Sequelize is just an argument

That could be written like that

return new init(Sequelize);

function init(Sequelize) {
    /* Preserve this pointer into forEach callbacks scope */
    var self = this;

    this.types = {
      'string'  : Sequelize.STRING,
      'text'    : Sequelize.TEXT,
      'integer' : Sequelize.INTEGER,
      'int'     : Sequelize.INTEGER,
      'decimal' : Sequelize.DECIMAL,
      'date'    : Sequelize.DATE,
      'boolean' : Sequelize.BOOLEAN,
    };

    /* Convert the Agence model Syntax to Sequelize syntax */

    this.parse = function(model) {

      /* Convert model Agence attributes to Sequelize types attribs */
      function toSequelizeTypes(attributes) {
        return mapValues(attributes, function(attribute) {
          var attribSettings    = cloneDeep(attribute);
          attribSettings.type   = self.types[attribSettings.type];
          return attribSettings
        });
      }

      return {
        tableName: model.tableName,
        attributes : toSequelizeTypes(model.attributes),
        hooks : model.hooks || {},
        classMethods : model.classMethods || {},
        instanceMethods : model.instanceMethods || {}
      };
    };

  }
Konrad
  • 21,590
  • 4
  • 28
  • 64