Get Data Router
Create routes quickly and easily with the independent get-data-router module
Создавайте маршруты быстро и легко с независимым модулем get-data-router
This is a Node.js module available through the npm.
$ npm install get-data-router
This module is designed to create routing from files. The name of your file automatically becomes the name of the route. You can create all possible http protocol protocols in your route
The module is connected through a standard function in Node.js require
const getDataFile = require('get-data-router')
The function is exported to the getDataFile constant.
The function is called and it takes on 2 arguments (path - required, callback - optional)
- path - path to the folder with your files for creating routes
project/
├── node_modules/
├── public
├── routers
│ ├── user/
│ │ ├── add.js
│ │ └── edit.js
│ ├──user.js
│ └──index.js
├── router.js
└── index.js
const getDataFile = require('get-data-router')
const data = getDataFile('./routers')
If you do not use callback, you must call the function in a variable or constant and it will give you, for example, the following object:
{
'./routers/index.js': { get: [AsyncFunction: getIndex] },
'./routers/user.js': {
get: { params: ':id', fn: [AsyncFunction: getUser] },
post: { fn: [AsyncFunction: postUser], mw: [ [Function: multerMiddleware] ] }
},
'./routers/user/add.js': { post: [AsyncFunction: setUser] },
'./routers/user/edit.js': { put: [AsyncFunction: editUser] }
}
Pros of using callback:
- Speeds up the development process
- Gives the finished route result
callback takes 4 arguments:
-
path - route path. Gives the finished path:
- ./routers/index.js -> /
- ./routers/user.js -> /user
- ./routers/user.js -> /user/:id
- ./routers/user/add.js -> /user/add
- ./routers/user/edit.js -> /user/edit
-
method - protocol method http
-
fn - function for route work
-
mw - middleware
Callback example uses framework express
const app = require('express'),
rout = app.Router(),
getDateFile = require('get-date-router')
getDateFile('./routers', (path, method, fn, mw) => {
if(mw != undefined) {
rout[method](path, ...mw, fn)
} else {
rout[method](path, fn)
}
})
module.exports = rout
Using the ./routers/user.js file as an example, consider creating a route
The example uses the multer module to download files and create an additional middleware.
const upload = require('multer')
async function getUser(req, res) {
res.send('Route works')
}
async function postUser(req, res) {
res.send('Route works')
}
module.exports = {
get: getUser,
post: {
fn: postUser,
mw: [ upload.single('file') ] /* Middleware - must always be an array */
}
}
const upload = require('multer')
async function getUser(req, res) {
res.send('Route works')
}
async function postUser(req, res) {
res.send('Route works')
}
module.exports = {
get: {
params: ':id', /* Rises after the main route */
fn: getUser
},
post: {
fn: postUser,
mw: [ upload.single('file') ] /* Middleware - must always be an array */
}
}