NodeJS Standard Way to Write Models with Sequelize

As we all know in our node js project there is one main file which is generally index.js or app.js. so if we put all code related to models file load so that is not an standard way of coding so for solving this problem we can create model directory, inside this directory we can create one index.js file in which we load all the models then call in models/index.js file in our main file. 


Node JS



Here is our app.js file:

"use strict"
require('dotenv').config(); //for calling process.env.VAR_NAME globally
const server = require('./config/server'),
express = require('express'),
app = express(),
port = server.port;

require('./src/models');

// all routing
app.get('/', (req, res) => {
res.send(server.appName)
})
app.use('/api', require('./src/routes/index'));

//listen server on mentioned port
app.listen(port, "0.0.0.0", () => {
console.log(`${server.appName} listening on port ${port}!`)
});


Let's say we have 2 models like below:

Model 1 User:

const Sequelize = require('sequelize');

module.exports = function (sequelize) {
const User = sequelize.define('users', {
user_id: {
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
user_name: {
type: Sequelize.STRING(100),
allowNull: true,
defaultValue: ""
},
email: {
type: Sequelize.STRING(100),
allowNull: true,
defaultValue: ""
},
password: {
type: Sequelize.STRING,
allowNull: true,
defaultValue: ""
},
status: {
type: Sequelize.INTEGER,
defaultValue: ""
}
},
{
timestamps: false,
}
);

return User;
};


Model 2 KalkineUser:

const Sequelize = require('sequelize');

module.exports = function (sequelize) {
const KalkineUser = sequelize.define('kalkine_users', {
id: {
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
full_name: {
type: Sequelize.STRING(100),
allowNull: true,
defaultValue: ""
},
mobile: {
type: Sequelize.STRING(13),
allowNull: true,
defaultValue: ""
},
country_code: {
type: Sequelize.STRING(10),
allowNull: true,
defaultValue: ""
},
isd_code: {
type: Sequelize.STRING(10),
allowNull: true,
defaultValue: ""
},
mobile: {
type: Sequelize.STRING(255),
allowNull: true,
defaultValue: ""
},
email: {
type: Sequelize.STRING(100),
allowNull: true,
defaultValue: ""
},
password: {
type: Sequelize.STRING,
allowNull: true,
defaultValue: ""
},
status: {
type: Sequelize.INTEGER,
defaultValue: ""
}
},
{
timestamps: false,
defaultScope: {
attributes: {
exclude: ['password']
}
}
}
);

return KalkineUser;
};


Now we create 1 models/index.js file for calling these two models:

const { Sequelize, QueryTypes } = require('sequelize');
const server = require('../../config/server');
const fs = require("fs");
const path = require("path");
const basename = path.basename(__filename);//index.js
const db = {};


// Option 3: Passing parameters separately (other dialects)
const sequelize = new Sequelize(server.dbName, server.dbUser, server.dbPass, {
host: server.dbHost,
dialect: 'mysql',
port: server.dbPort,
logging: false
});
// const User = require('./userModel')(sequelize);
// const KalkineUser = require('./kalkineUserModel')(sequelize);

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

sequelize
.authenticate()
.then(() => {
console.log('DB Connection has been established successfully.');
})
.catch((err) => {
console.log('Unable to connect to the database:', err);
});
const fetch = async() => {
    //row query
const [results, metadata] = await sequelize.query("SELECT * FROM users");
//console.log(results)
//console.log(metadata)
const users = await db.kalkine_users.findAll();
console.log(users)
}
fetch();


In above file we can see with the help of FS core module of node js we are here able to load all the models directly without adding one by one manually.

Now let's add some more code in models/index.js file to export all the models and use it in any controller or services.
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

Whole updated models/index.js file:
const { Sequelize, QueryTypes } = require('sequelize');
const server = require('../../config/server');
const fs = require("fs");
const path = require("path");
const basename = path.basename(__filename);//index.js
const db = {};


// Connect with DB
const sequelize = new Sequelize(server.dbName, server.dbUser, server.dbPass, {
host: server.dbHost,
dialect: 'mysql',
port: server.dbPort,
logging: false
});
// Check connection
sequelize
.authenticate()
.then(() => {
console.log('DB Connection has been established successfully.');
})
.catch((err) => {
console.log('Unable to connect to the database:', err);
});

// const User = require('./userModel')(sequelize);
// const KalkineUser = require('./kalkineUserModel')(sequelize);
fs.readdirSync(__dirname)
.filter((file) => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
.forEach((file) => {
const sModel = require(path.join(__dirname, file))(sequelize);
const model = sModel;
db[model.name] = model;
});

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

// const fetch = async() => {
// const [results, metadata] = await sequelize.query("SELECT user_id,email FROM users ORDER BY user_id DESC");
// //console.log(results)
// //console.log(metadata)
// const users = await db.kalkine_users.findAll();
// console.log(users)
// }
// fetch();

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

module.exports = db;



Lets call it in service for db query management:
const db = require('../models');

const getAllUsers = async() => {
const users = await db.kalkine_users.findAll();
return users;
}

module.exports = {
getAllUsers
};


Now let's call this service in rest APIs within controller function:
const userService = require('../services/userService');

const getAllUsers = async(req,res,next) => {
try{
console.log('Users listing api called.');
const data = await userService.getAllUsers();
return res.send(data);
}catch(err){
console.log(err.message);
}
}

module.exports = {
getAllUsers
}


That's it, I hope this blog will be helpful for you as a developer.
Happy Coding !

Comments

Popular posts from this blog

JavaScript Logical Output Based Interview Questions

Create and Deploy AWS SAM Application

Deploy Angular Build With Express JS Project