GithubHelp home page GithubHelp logo

Comments (7)

wilo087 avatar wilo087 commented on May 9, 2024 2

Here is an example using require

./models/index.js

const dotenv = require('dotenv');
const fs = require('fs');
const path = require('path');
const { Sequelize, DataTypes } = require('sequelize');

const filebasename = path.basename(__filename);
const db = {};

// Get env var from .env
dotenv.config()
const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_FORCE_RESTART } = process.env;

const config = {
  host: DB_HOST,
  dialect: 'mysql',
  dialectOptions: {
    charset: 'utf8',
  }
}

const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, config);

fs
  .readdirSync(__dirname)
  .filter((file) => {
    const returnFile = (file.indexOf('.') !== 0)
      && (file !== filebasename)
      && (file.slice(-3) === '.js');
    return returnFile;
  })
  .forEach((file) => {
    const model = require(path.join(__dirname, file))(sequelize, DataTypes)
    db[model.name] = model;
  });


Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

const sequelizeOptions = { logging: console.log, };

// Removes all tables and recreates them (only available if env is not in production)
if (DB_FORCE_RESTART === 'true' && process.env.ENV !== 'production') {
  sequelizeOptions.force = true;
}

sequelize.sync(sequelizeOptions)
  .catch((err) => {
    console.log(err);
    process.exit();
  });

module.exports = db;

./models/User.js

'use strict';

import cryp from 'crypto';

module.exports = function (sequelize, DataTypes) {
  const User = sequelize.define('User', {
    email: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
      validate: {
        isEmail: { msg: "Please enter a valid email addresss" }
      },
      isEmail: true
    },
    password_hash: { type: DataTypes.STRING(80), allowNull: false },
    password: {
      type: DataTypes.VIRTUAL,
      set: function (val) {
        //this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated
        this.setDataValue('password_hash', cryp.createHash("md5").update(val).digest("hex"));
      },
      validate: {
        isLongEnough: function (val) {
          if (val.length < 8) {
            throw new Error("Please choose a longer password");
          }
        }
      }
    },
    role: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    active: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 1
    }

  }, {
    classMethods: {
      associate: function (models) {
        // User.belongsTo(models.Department, { foreignKey: { allowNull: false } });
        // User.belongsTo(models.Position, { foreignKey: { allowNull: false } });
        // User.belongsTo(models.Profile, { foreignKey: { allowNull: false } });

        // User.hasMany(models.Report, { foreignKey: { allowNull: false } });
        // User.hasMany(models.Notification, { foreignKey: { allowNull: false } });
        // User.hasMany(models.Response, { foreignKey: { allowNull: false } });

      }
    },

    timestamps: true,

    // don't delete database entries but set the newly added attribute deletedAt
    // to the current date (when deletion was done). paranoid will only work if
    // timestamps are enabled
    paranoid: false,

    // don't use camelcase for automatically added attributes but underscore style
    // so updatedAt will be updated_at
    underscored: true
  });
  return User;
};

.env

DB_HOST=localhost
DB_USER=wilo087
DB_PASS=temp
DB_NAME=database_name
DB_FORCE_RESTART=true #Remove and create tables

Full example on:
https://github.com/wilo087/pethome_raffle_backend/tree/develop

from express-example.

rakeshlanjewar avatar rakeshlanjewar commented on May 9, 2024 1

As documentation here https://sequelize.org/master/manual/models-definition.html show that it is deprecated.

The documentation suggests to use require, But i am not sure how to use it.
can you provide a small snippet.

//load all Models from models directory dynamically
fs.readdirSync(__dirname).filter(file => {
  return (file.indexOf('.') !== 0) && (file !== path.basename(__filename)) && (file.slice(-3) === '.js');
}).forEach(function (filename) {
  database.import(path.join(__dirname, '', filename));
});

const models = database.models;

// Set up data relationships
Object.keys(models).forEach(name => {
  if ('associate' in models[name]) {
    models[name].associate(models);
  }
});

from express-example.

scucchiero avatar scucchiero commented on May 9, 2024 1

This solution reading files from the filesystem seems so nasty to me.
What about an index in the models folder?
I can make a PR.

from express-example.

papb avatar papb commented on May 9, 2024 1

Hello everyone, I created a new example from scratch. The new example does not use sequelize.import anymore.

from express-example.

wilo087 avatar wilo087 commented on May 9, 2024

You can use only index file on the model folder, but, what happens if you have more than 30 models with associations, validations functions, hooks, virtual fields, etc.?

Exactly, your code going to look nasty as f**k.

from express-example.

c0dezer019 avatar c0dezer019 commented on May 9, 2024

using require() assumes that the package in question isn't using ES5-6 syntax. require isn't a thing in ES modules. What would I use as an alternative then?

from express-example.

ephys avatar ephys commented on May 9, 2024

If you're using esm, use import. Sequelize works with both module systems, but this boilerplate is written in cjs

from express-example.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.