express-path-router
Description
This module allows to mount an express API based on a file architecture and facilitate the middleware reuse.
Installation
yarn add express-path-router
Usage
Following the classic express routing way, a huge service may end with a really fastidious bunch of code (even when splitted in multiple files). This module allows to avoid this by loading the routing from file architecture.
Example:
API target:
app;app;app;
File system:
|-- index.js
|-- api
|-- cities
| |-- :cityId
| |-- get.js
|-- companies
|-- post.js
|-- :companyId
|-- get.js
Then, you can load it automatically
var router = ; router;
Documentation
Each API point (file like .../api/companies/:companyId/get.js
) is based on the following structure:
moduleexports = pattern: string middlewares:
pattern
- string - optional - pattern replacement (ie: '(*)' will replace aget:/products/:id
byget:/products/(*)
)middlewares
- function[] - optional - list of middlewares to add on the routecallback
- function - API point payload
A syntactic sugar may be used in the module, by returning a function or an array of function. Thoses functions will be set as middleware and callback.
_.js
Specials files _.js
may be added everywhere in the file structure. Thoses files middlewares will be added on each API point in their sub-structure.
Example:
|-- companies
|-- _.js {middlewares: [A, B, C]}
|-- post.js {middlewares: [D], callback: E}
|-- :companyId
|-- _.js {middlewares: [F, G]}
|-- get.js {middlewares: [H, I, J], callback: K}
This example will produce the equivalent of:
app;app;
load(config, callback)
-
config
- objectapp
- object - express applicationpath
- string - path to loadprefix
- string - optional - prefix to add on the routehook
- function - optional - function call before each route definition to modify the middleware stack
-
callback
- function - optional
returns undefined
when using callback, else a promise.
hook(middlewares, data)
middlewares
- function[]data
- objectfile
- string - working file (ie..../api/companies/:companyId/get.js
)method
- string - http verb (ie.get
)module
- object - module loaded (ie.get.js
module)modules
- object[] - ordered list of module (ie._.js, ...., get.js
module list)route
- string - target route (ie.companies/:companyId
)
The hook function is useful to modify the middleware stack before adding the route. You can either modify the middlewares parameters or return a new array.
Example:
var auth = ;var token = ; router;