mojahed-express-controller
v1.0.2
Published
Implements Controller, Middleware and Route of MVC using express.
Downloads
3
Maintainers
Readme
Installation
Using npm:
$ cd <your-project-directory>
$ npm i mojahed-express-controller
Inside package.json add to scripts :
"make:controller" : "node ./node_modules/mojahed-express-controller/commands/make_controller.js",
"make:middleware" : "node ./node_modules/mojahed-express-controller/commands/make_middleware.js",
"make:controller-structure" : "node ./node_modules/mojahed-express-controller/commands/structure.js"
run :
$ npm run make:controller-structure
Usage
Create controller :
$ npm run make:controller UserController
User Controller will be created inside project-directory/controllers/
Inside UserController.js file :
class UserController {
static dashboard(req, res)
{
res.send('This is dashboard');
}
}
Create middleware :
$ npm run make:middleware AuthorizationMiddleware
AuthorizeMiddleware will be created inside project-directory/middlewares/
Inside AuthorizationMiddleware.js file :
function AuthorizationMiddleware (req, res, next) {
let token = req.header('x-auth-token');
if(! token) req.status(401).send("Access denied ! No token provided");
if(/*if token is not valid*/) req.status(400).send('Invalid token');
next();
}
Use controller and middleware inside routes
Inside routes/web.js file :
Top :
const UserController = require('../controllers/UserController');
const AuthorizationMiddleware = require('../middlewares/AuthorizationMiddleware');
Inside webRoute function :
Route.get('/dashboard', [ AuthorizationMiddleware ], UserController.dashboard);
Finally :
Inside index.js :
const ExpressApp = require('./routes/route');
ExpressApp.listen(3000);
run :
$ node index.js