get-data-router
v1.1.1
Published
This plugin will help facilitate work with routes.
Downloads
18
Maintainers
Readme
Installation
This is a Node.js module available through the npm.
$ npm install get-data-router
Principle of operation
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 called and it takes on 2 arguments (path - required, callback - optional)
- path - path to the folder with your files for creating routes
Work without callback
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] }
}
Work using callback
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
Route creation
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 */
}
}