Send data between different routes in Nodejs (Using Sessions)

Send data between different routes in Nodejs (Using Sessions)

We going to use session to make a class for managing our data. we will create an existence as a Javascript  class with few static methods to manipulate data and save or remove a particular session.

There is just few steps to do it.

Step one: Add some dependencies:

To use get and set cookies and create session you will need these two library.

npm i express-session --save
npm i cookie-parser --save

Step two: Add this piece of code in specific place before your routes:

You can add them on your Server.js file or in a particular middleware between your routes. in my case there is a file name startup.js and i call it in Server.js.

startup.js

const cookieParser = require('cookie-parser')
const session = require('express-session')


module.exports = function (app) {


    app.use(morgan('dev'))
    app.use(cookieParser())
    app.use(session({
    key: 'user',
    secret: '564653456fsd3fd76f3',
    resave: false,
    saveUninitialized: false,
    cookie: {
        expires: 600000
    }
}));


}

server.js

const express = require('express')
const app = require('express')()
const mongoose = require('mongoose')
global.config = require('./modules/utilities/config')
const Startup = require('../middlewares/startup') //--> Define it


mongoose.connect('mongodb://127.0.0.1/test',


{ useNewUrlParser: true })


Startup(router) //----> Use it here


const webRouter = require('./modules/routes/web')


app.use('/', webRouter)


app.listen(config.port, () => { 


console.log(`server running at port ${config.port}`)


})

Step three: Create a Bundle class.

Create a file named bundle.js in a favorite directory in my case there is in my utilities folder under the root path.

I want explain it a little. in these class you have three method as you can see they are Static because of their usage you will see in forward. (if you do know anything about static methods please search it on google).

Whole methods follow one rule (Models Error and Message) the Models include all of your data consist of Arrays of object or just a single Json object again Errors and Message can be fill when you need pass an error or specific message to another routes to show on a View. 

bundle.js

module.exports = class bundle {

    static createBundle(models, errors, message) {


        return {


            models: models,
            errors: errors,
            message: message
        }
    }

    static setBundle(req, models, errors, message, bundleName){


        if (bundleName) {


            req.session[bundleName] = {


                models: models,
                errors: errors,
                message: message,
            }

        } else {


            req.session.data = {


                models: models,
                errors: errors,
                message: message,
            }
        }
    }



    static getBundle(req,bundleName) {


        if (bundleName) {
            const data = req.session['bundleName']
            req.session.data = null


            if (!data) {


                return {

                    models: null,
                    errors: null,
                    message: null


                }
            } else {

                return data

            }
        } else {


            const data = req.session.data


            req.session.data = null


            if (!data) {


                return {


                    models: null,
                    errors: null,
                    message: null

                } 
            } else {

                return data
            }
        }
    }
}

Know let me to explain the functions one by one.

1.createBundle: this function will return you an object that contains our three universal object it will be used when you want to pass your data to a view.

2.setBundle: this function has responsibly of saving your data in a specific session and prevent loosing data during a http request the last parameter of this function is optional to use if you want to set a particular session you can name it by bundleName parameter.

3.getBundle: When you redirected to another route so you need to get data from the session it so easy for you to just call getBundle function and save the data in a variable or directly pass it to a View. keep in your mind if your bundle has been sat by a specific name you should get it by same name.

Step four: Use your bundle class.

According to the explains above now you can use the bundle class very easy but i will take you some example of how it is work.

controller.js

const Validator = require('../../utilities/validator')
const Database = require('../../utilities/database')
const Transform = require('../../transforms/v1/transform')
const Config = require('../../utilities/config')
const Auth = require('../../utilities/auth')
const Bundle = require('../../utilities/bundle') ---> Define it here
const File = require('../../utilities/files')




module.exports = class controller{


constructor() {


    this.Validator = Validator
    
    this.Bundle = Bundle ---> use it here
    
    this.Database = Database 
    
    this.Transform = Transform
    
    this.Config = Config
    
    this.Auth = Auth
    
    this.File = File
    
    }


}

group.js

const express = require('express')
const router = express.Router()
const groupController = require('../../controllers/web/groupController')
const Authorization = require('../middlewares/authentication')
const uploadMid = require('../middlewares/upload.js')
const multer = require('multer')
const upload = multer({ storage: uploadMid.setGroup });


router.get('/list', Authorization.sessionAuthorize, groupController.list.bind(groupController))


router.get('/create', Authorization.sessionAuthorize, groupController._create.bind(groupController))


router.post('/create', Authorization.sessionAuthorize, upload.single('photo'), groupController.create.bind(groupController))


router.get('/remove/:id', Authorization.sessionAuthorize ,groupController.remove.bind(groupController))


module.exports = router

groupController.js

const path = require('path')
const Controller = require('./controller')


class GroupController extends Controller{


    _create(req, res) {
        return res.render(path.resolve('modules/views/pages/group/create'),this.Bundle.getBundle(req))
    }




    remove(req, res) {
         
        this.Database.Group.findByIdAndRemove(req.params.id, (error, doc) => { 
            if (error) {
                this.Bundle.setBundle(req, null, error, "Check the Errors Bellow.")
                
            } else if (doc) {
                this.Bundle.setBundle(req, null, null, "Group Has Been Deleted Successfuly.")
                
            } else {
                this.Bundle.setBundle(req, null, ["Error has occured while get data."], "Check the Errors Bellow.")               
                 
            }
            return res.redirect('../list')
        })
    }


    list(req, res) {


        const bundle = this.Bundle.getBundle(req)


        this.Database.Group.find((error, groups) => { 
            if(error)
                return res.render(path.resolve('modules/views/pages/group/list'), this.Bundle.createBundle(null, error, "Check the Errors Bellow."))
            
            if (groups)
                return res.render(path.resolve('modules/views/pages/group/list'), this.Bundle.createBundle(groups, bundle.errors, bundle.message))
            
            else
                return res.render(path.resolve('modules/views/pages/group/list'), this.Bundle.createBundle(null, ["Error has occured while get data."], "Check the Errors Bellow."))
        })
    }


}


module.exports = new GroupController

I wish you were familiar with this small and tricky way it just take you a good vision to how you can implement your bundle service it is so obvious that you can change it in a way your are easy to use.

At last i am eager to hear your feedback and let me to help you if there is something unclear in this article.

要查看或添加评论,请登录

Mo Ravaei的更多文章

社区洞察

其他会员也浏览了