Express Auto Routes
中文介绍请点击 这里
In most of the time, we need to mount handlers / controllers to routes manually.
e.g.
/** now we are in routes/index.js **/var homeRouter = userCtrl = ; // Method 1: mount a sub router to a path. kinda code splitting but still complicatedapp; // Method 2: mount controllers to routes one by one, sucksapp;app;app;...
It's hardly elegant, so here comes express-auto-routes.
Firstly, npm install express-auto-routes --save
e.g.
/** now we are in app.js **/var path = express = app = ; var autoRoutes = app; // you don't need `routes` folder any more; // auto mounting... done! // ...other configures app;
/** now we are in controllers/hello/world.js **/exports { res;};
Then visit localhost:8080/hello/world
, you will see hello world
The magic is just globbing all the valid controller files and resolve them based on relative path.
Since we glob files recursively, without doubt it supports unlimited sub folders.
e.g.
controllers/a/b/c/d/e/f/gjs localhost:8080/a/b/c/d/e/f/g
Here I highly recommend you checking out the example/
folder for more detail.
> npm install
> npm run example
[AutoMount] use /home/
[AutoMount] use /user/
[AutoMount] use /user/logout/
[AutoMount] all /user/setting/
[AutoMount] get /home/foo/bar/world/
[AutoMount] get /user/setting/:uid
[AutoMount] delete /user/logout/:uid
[AutoMount] get /home/foo/hello/
[AutoMount] get /home/foo/bar/
[AutoMount] get /user/logout/
[AutoMount] get /user/:uid?
[AutoMount] get /home/foo/
[AutoMount] get /home/xyz/
[AutoMount] post /setting
[AutoMount] get /login
[AutoMount] get /home/
[AutoMount] post /login
[AutoMount] put /user/
[AutoMount] post /log
[AutoMount] get /
then visit localhost:8080
and test the above APIs with Postman
[ A more practical project ] checkout Message Board API which based on this package.