Last active
January 14, 2016 00:31
-
-
Save sunilmurali/e635d6eca4894aed29b8 to your computer and use it in GitHub Desktop.
Load all the routes defined in the route folder;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
================ WIP ============= | |
/** | |
* Express router needs to be defined and each file module.exports should return the router | |
*/ | |
var fs = require ('fs' ) ; | |
var _ = require ('lodash'); | |
var routes = {}; | |
/* | |
Folder Structure: | |
prj_folder | |
--app.js // doesnt matter | |
--route | |
-- v1 | |
--route_file1.js | |
--route_sub | |
-- route_file2.js | |
routes will be translated for above structure as | |
/v1/{{routes defined in route_file1}} | |
/v1/route_sub/{{routes defined in route_file2}} | |
*/ | |
var topDir = __dirname ; | |
module.exports = function (app) { //function ( req , res , next ) { | |
var path = '/v1' ; // todo change this to read all the subfolders for the 'route' | |
detRoutes (app, path ) ; | |
} ; | |
/** | |
* route path is generated based on the folder structure | |
* if file then currentpath/filename will be the route | |
*/ | |
function detRoutes (app, path ) { | |
var pathContents = fs.readdirSync( topDir + path ) ; | |
if ( pathContents ) { | |
for ( var i=0;i<pathContents.length; i ++ ) { | |
var relPath = path + '/' + pathContents[i] ; | |
var childPath = topDir + relPath ; | |
var stat = fs.lstatSync( childPath ) ; | |
if ( stat.isFile ( ) ) { | |
var router = require ( childPath ) (); | |
var subroute = getFileNameWithoutExtension ( pathContents[i] ) ; | |
var routeName = path + '/' + subroute ; | |
routes[routeName] = router ; | |
app.use ( routeName , router ) ; | |
} | |
else if ( stat.isDirectory () ) { | |
detRoutes ( app, relPath ) ; | |
} | |
} | |
} | |
} | |
function getFileNameWithoutExtension ( filename ) { | |
return filename.substring (0,filename.lastIndexOf('.')) ; | |
} | |
function getFileExtension ( filename ) { | |
return filename.substring (filename.lastIndexOf('.')) ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment