12 October 2019

NodeJS ExpressJS: Controller [EX-09]


Controller
/controller/user.controller.js
user.controller.js
const db = require('../db/index').lowDB;
var ids = require('short-id');

module.exports.index = function (req, res) {
    res.render('users/index', {
        users: db.get('users').value()
    })
}

module.exports.create = function (req, res) {
    res.render('users/create')
}

module.exports.postCreate = function (req, res) {
    // Add a post
    req.body.id = ids.generate();
    db.get('users').push(req.body).write()
    res.redirect('/users');
}

module.exports.get = function (req, res) {
    var id = req.params.id;
    res.render('users/view', {
        user: db.get('users').find({
            id: id
        }).value()
    })
}

module.exports.search = function (req, res) {
    var q = req.query.name;
    var matchUsers = db.get('users').value().filter(f => f.name.toLocaleLowerCase().indexOf(q.toLocaleLowerCase()) !== -1);
    res.render('users/index', {
        users: matchUsers
    })
}

/users/user.route.js
user.route.js
const express = require('express')
const router = express()

var controller = require('../controller/user.controller');

// GET method route
router.get('/', controller.index);

// GET method route
router.get('/create', controller.create);

// GET by id
router.get('/:id', controller.get);

// POST create user
router.post('/create', controller.postCreate);

// GET method route
router.get('/search/name', controller.search);

module.exports = router;

<< back | next >>

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang