Skip to content

Commit

Permalink
Exclude controller files (#9)
Browse files Browse the repository at this point in the history
* exclude files and login

* read me and doc

* readme update

* readme fix

* readme fix 2

* readme fix 3
  • Loading branch information
benhurdavies authored Nov 28, 2017
1 parent 0179d6e commit 5821c94
Show file tree
Hide file tree
Showing 7 changed files with 195 additions and 28 deletions.
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
[![Build Status](https://travis-ci.org/benhurdavies/magic-router.png?branch=master)](https://travis-ci.org/benhurdavies/magic-router)
[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/benhurdavies/magic-router)
[![HitCount](http://hits.dwyl.io/benhurdavies/benhurdavies/magic-router.svg)](http://hits.dwyl.io/benhurdavies/benhurdavies/magic-router)
[![GitHub license](https://img.shields.io/github/license/benhurdavies/magic-router.svg)](https://github.com/benhurdavies/magic-router/blob/master/LICENSE)

</div>

Expand Down Expand Up @@ -34,10 +35,23 @@ const app = express();
import magicRouter from 'magic-router';

//adding all contollers..

// magicRouter.addAll(express_app_instance, options);
magicRouter.addAll(app, { dirPath: './controllers' });

```
* Usage [example](./example)
* Usage in [example](./example)

##### Exclude some controller files from magic-routering

```javascript
magicRouter.addAll(app, {
dirPath: '../../example/controllers',
// excluding files
exclude: ['../../example/controllers/auth.js'],
});
```
* Usage in [exclude file test](https://github.com/benhurdavies/magic-router/blob/d1e20a4b67224f92e16a2188af049a194ad59866/test/example/excludeFiles.js#L77)

The developers need to focus only on the controllers.

Expand Down Expand Up @@ -117,6 +131,10 @@ those only if you need to override the default behaviors.

### Release version

#### 1.0.8 : Exclude controller files
* Feature to exclude some controller files from magic-routering.
* Logging the router details.

#### 1.0.7 : Exception handling
* All action methods in controller are exception handled, If any exception caused inside an action, Error will forewarded automatically to (_next(err);_) outside/global (app.js) error hooked methods. The implemented at [example](./example).
* Added [test](./test) for testing the framework.
Expand Down
15 changes: 15 additions & 0 deletions example/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export default {
type: {
login: 'post',
},

// this will access by /auth/login as POST request
login(req, res) {
const { email, password } = req.body;
if (email === '[email protected]' && password === 'password') {
return res.send({ isAuthenticated: true });
} else {
return res.send({ isAuthenticated: false });
}
},
};
4 changes: 3 additions & 1 deletion example/server.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import express from 'express';
import consign from 'consign';
import http from 'http';
import bodyParser from 'body-parser';

import magicRouter from '../src/magic-router';

const port = 3000;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// adding contollers..
magicRouter.addAll(app, { dirPath: './controllers' });
Expand Down
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "magic-router",
"version": "1.0.7",
"version": "1.0.8",
"description": "routing pattern and high productive way for bulding mvc/api projects",
"main": "./distribution/magic-router.js",
"scripts": {
Expand All @@ -26,6 +26,7 @@
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"babel-register": "^6.26.0",
"body-parser": "^1.18.2",
"chai": "^4.1.2",
"chai-http": "^3.0.0",
"eslint": "^4.11.0",
Expand Down Expand Up @@ -59,5 +60,9 @@
"magicRouter"
],
"author": "Benhur Davies",
"license": "MIT"
"license": "MIT",
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
}
}
22 changes: 17 additions & 5 deletions src/loadFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,26 @@
import consign from 'consign';
import path from 'path';

export default (app, dirPath, callerPath) => {
let pathInfo = makePath(dirPath, callerPath);
consign({ cwd: pathInfo.cwd })
.include(pathInfo.dir)
.into(app);
export default (app, options) => {
let pathInfo = makePath(options.dirPath, options.callerPath);
let _consign = consign({ cwd: pathInfo.cwd }).include(pathInfo.dir);

//excluding files or directorys.
options.exclude.forEach(item => {
let eachPathInfo = makePath(item, options.callerPath);
let _filePath = excludePath(pathInfo.cwd, eachPathInfo);
_consign.exclude(_filePath);
});

_consign.into(app);
return pathInfo;
};

function excludePath(rootPath, pathInfo) {
let remainPath = pathInfo.cwd.replace(rootPath, '');
return path.join(remainPath, pathInfo.dir);
}

function makePath(dirPath, callerPath) {
let _path = path.join(callerPath, '..', dirPath, '..');
let dir = path.basename(dirPath);
Expand Down
47 changes: 28 additions & 19 deletions src/magic-router.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
'use strict';

import path from 'path';

import loadFile from './loadFile';
import caller from './caller';

const pack = require(path.join(__dirname, '..', 'package'));

const ROUTER_NAME = 'router';
const TYPE_NAME = 'type';
const BEFORE_CONTROLLER_NAME = 'beforeController';
Expand All @@ -12,31 +16,32 @@ class magicRouter {
constructor() {
this.defaultOptions = {
dirPath: '',
exclude: [],
};
this.options = null;
this.app = null;
}

addAll(app, options) {
this.app = app;
this.makeOptions(options);
//loading controller files
let pathInfo = loadFile(this.app, this.options);
//adding router.
console.log(`${pack.name} v${pack.version} Initialized`);
this.addRouters(pathInfo.dir);
}

makeOptions(options) {
//setting options
let cwd = process.cwd();
this.options = {
...this.defaultOptions,
...options,
//if you are creating an npm module with magic router as an internal module,
//please pass the relative path of the controllers of the applicaiton that consumes your module
//eg: magicRouter.addAll(app, { dirPath: './controllers' });
callerPath: caller(1),
callerPath: caller(2),
};
//loading controller files
let pathInfo = loadFile(
this.app,
this.options.dirPath,
this.options.callerPath
);
//adding router.
this.addRouters(pathInfo.dir);
}

addRouters(appNameSpace) {
Expand Down Expand Up @@ -75,6 +80,7 @@ class magicRouter {
);

// adding current method routing
console.log(`+ ${fullRoute}`);
this._addRoute(
requestType,
fullRoute,
Expand All @@ -87,13 +93,13 @@ class magicRouter {
}

_addRoute(requestType, routePath, HandlerMethod, app) {
try {
app[requestType](routePath, (req, res, next) => {
app[requestType](routePath, (req, res, next) => {
try {
HandlerMethod(req, res, next);
});
} catch (err) {
next(err);
}
} catch (err) {
next(err);
}
});
}

getPropertyFromHandler(handler, methodName, optionKey) {
Expand Down Expand Up @@ -127,8 +133,10 @@ class magicRouter {

addBeforeControllers(handler, controllerName, app) {
let beforeControllers = this.getBeforeControllers(handler);
beforeControllers.forEach(method => {
this._addRoute(RequestType.USE(), `/${controllerName}`, method, app);
beforeControllers.forEach((method, key) => {
let routePath = `/${controllerName}`;
console.log(`+ beforeControllers(${key}) => ${routePath}`);
this._addRoute(RequestType.USE(), routePath, method, app);
});
}

Expand All @@ -150,7 +158,8 @@ class magicRouter {
BEFORE_ACTION_NAME
);
if (beforeAction && Array.isArray(beforeAction)) {
beforeAction.forEach(method => {
beforeAction.forEach((method, key) => {
console.log(`+ beforeAction(${key}) => ${route}`);
this._addRoute(requestType, route, method, app);
});
}
Expand Down
106 changes: 106 additions & 0 deletions test/example/excludeFiles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import chai from 'chai';
import chaiHttp from 'chai-http';

import express from 'express';
import http from 'http';
import bodyParser from 'body-parser';

import magicRouter from '../../src/magic-router';

const expect = chai.expect;
const should = chai.should();
let _port = 3500;

// creating custom server
function getServer(addRouter) {
const port = _port++;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

addRouter(app);

app.use('*', function(req, res) {
res.send({ msg: 'no router defined' });
});

//error handling
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
errorMessage: err.message,
error: err,
});
});

var server = http.createServer(app);
return server.listen(port);
}

describe('include all controller test', () => {
let includeAllController = function(app) {
magicRouter.addAll(app, { dirPath: '../../example/controllers' });
};
const server = getServer(includeAllController);
const _req = chai.request(server);

after(done => server.close(done));

it('/user/get', done => {
_req.get('/user/get').end((err, res) => {
console.re;
res.should.have.status(200);
res.body.msg.should.equal('hello user');
res.body.name.should.equal('user');
// checking before_Controller worked or not
res.header.beforecontroller.should.equal('controllerLogger1');
done();
});
});

it('/auth/login post', done => {
_req
.post('/auth/login')
.send({ email: '[email protected]', password: 'password' })
.end((err, res) => {
res.should.have.status(200);
res.body.isAuthenticated.should.equal(true);
done();
});
});
});

describe('exclude some controller test', () => {
let includeAllController = function(app) {
magicRouter.addAll(app, {
dirPath: '../../example/controllers',
exclude: ['../../example/controllers/auth.js'], // excluding files
});
};
const server = getServer(includeAllController);
const _req = chai.request(server);

after(done => server.close(done));

it('/user/get', done => {
_req.get('/user/get').end((err, res) => {
res.should.have.status(200);
res.body.msg.should.equal('hello user');
res.body.name.should.equal('user');
// checking before_Controller worked or not
res.header.beforecontroller.should.equal('controllerLogger1');
done();
});
});

it('/auth/login post', done => {
_req
.post('/auth/login')
.send({ email: '[email protected]', password: 'password' })
.end((err, res) => {
res.should.have.status(200);
res.body.msg.should.equal('no router defined');
done();
});
});
});

0 comments on commit 5821c94

Please sign in to comment.