MVCS architecture in node & express
Model view controller Service
Model To define the ORM.View Represents how the data will show in the page Controller processing the request and response.
Service can have business logic & implemented here
So let's see how to implement MVCS in Node & Express.
Project directory structure
Here I am using sequelize as ORM.
Main.js is the initial loading file for our application
//main.js
var exp = require('express')
var app = exp();
var api = require('./api');
app.use(exp.json());
app.use('/api',api);
app.use('/web',web);
app.listen(8080,()=>{
console.log("server started..");
})
Recommended by LinkedIn
Below model is the ORM of our user table. Here we are using sequelize.
//UserModel.js
const { DataTypes } = require('sequelize');
const {sequelizeObj} = require("../config/DbCon");
const UserModel = sequelizeObj.define('user', {
// Model attributes are defined here
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING
// allowNull defaults to true
},
password: {
type: DataTypes.STRING
// allowNull defaults to true
}
});
module.exports = { UserModel }
Our business logic will be implemented in this service.
//UserService.js
const { UserModel } = require('../model/UserModel');
const {sequelizeObj} = require("../config/DbCon");
class UserService{
async getAllData(){
await sequelizeObj.sync();
let userDbData = await UserModel.findAll();
return userDbData;
}
async login(uname,pwd){
await sequelizeObj.sync();
console.log(uname,pwd);
let userDbData = await UserModel.findOne({where:{"email":uname,"password":pwd}});
if(userDbData == null){
throw 'NO USER FOUND';
}
return userDbData.dataValues;
}
async register(){
await sequelizeObj.sync();
await UserModel.create({
"name":"tesrt",
"email":"test@gmail.com",
"password":"test"
})
}
}
module.exports ={ UserService};
//api.js
var exp = require('express');
const { UserService } = require('./Service/UserService');
var router = exp.Router();
let userService = new UserService();
router.get('/getAll',async (req,res)=>{
let dbData = await userService.getAllData();
res.json(dbData);
})
router.post('/login',async (req,res)=>{
try{
let uname = req['body']['name'];
let pwd = req['body']['pwd']
let dbData = await userService.login(uname,pwd);
res.json(dbData);
}catch(e){
res.status(400);
res.json({"Error":"Error "+e})
}
})
router.post('/register',async (req,res)=>{
try{
await userService.register();
res.json({"message":"data inserted"});
}catch(e){
res.status(400);
res.json({"Error":"Error "+e})
}
})
module.exports=router;
node main.js will run our app successfully.