MVCS architecture in node & express

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

Article content

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..");

})        


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.        

Link for source code

To view or add a comment, sign in

More articles by Sri Praveen

  • youtube clone using java + spring boot Part-1

    In this blog about YouTube Clone part1. creating mysql tables for this application users, Videos, likes comments, Now…

    1 Comment
  • Create & Verify JWT in nodejs

    #nodejs #jwt In this article we are going to see how to generate the token in NodeJs. Json web token(JWT) is used for…

  • Send Email in NodeJs

    In this article we are going to see how to send an email from node JS application. In server side application sending…

  • Template Engine in nodejs & Expressjs(part -1)

    Hi in this article we are going to see how to render html in express.let see the steps .

  • How to connect node & mysql with Sequelize ORM.

    Most of the modern applications will prefer to use any one ORM framework (Object Relational mapping) to connect the…

  • How to read excel in nodejs and insert into mysql

    In this article we are going to see how to read the excel in NodeJS and insert the data into mysql. So we need to…

  • Node with mysql

    Hi in this article we are going to see how to connect Node app with mysql.let read further.

  • 12 points to become javascript developer.

    Variable declarations(var let const) Condition,loops Arrays & objects Set & MAP Arrow functions Async and await Rest…

Insights from the community

Others also viewed

Explore topics