@ikrbasak/express-file-router
v0.2.0
Published
File-based routing system for Express
Downloads
1
Maintainers
Readme
Express File Router
File-based routing for Express.js without any 3rd party dependency.
Install
npm i @ikrbasak/express-file-router
Getting started
// main.ts
import express from 'express';
import path from 'node:path';
const app = express();
await createRoute(app, {
// Optional config. Determines the 'root' for routes. Default: 'routes'.
directory: path.join(__dirname, 'routes'),
});
app.listen(9000);
// routes/index.ts
export const get: RequestHandler = (req, res) => {
res.json({ ping: 'pong' });
};
Route matching
Given the following folder structure:
├── app.ts
└── routes
├── index.ts (1)
├── posts
│ ├── :pid
│ │ └── index.ts (2)
│ └── index.ts (3)
└── users
├── :uid.ts (4)
└── index.ts (5)
the route mapping would be as following:
(1) /routes/index.ts -> '/'
(2) /routes/posts/:pid/index.ts -> '/posts/:pid'
(3) /routes/posts/index.ts -> '/posts'
(4) /routes/users/:uid.ts -> '/users/:uid'
(5) /routes/users/index.ts -> '/users'
Method matching
/*
'middlewares' serves as common place to write
middlewares that are used in each of the HTTP methods.
*/
// Option 1
export const middlewares: RequestHandler = (req, res, next) => {
// some custom middleware logic
next();
};
// Option 2
export const middlewares: RequestHandler[] = [
commonMiddleware1,
commonMiddleware2,
];
/*
Resolves 'GET' request to the particular route
*/
// Option 1
export const get: RequestHandler = (req, res) => {
return res.json({
fingerprint: req.fingerprint,
url: req.originalUrl,
file: __filename,
});
};
// Option 2
export const get: RequestHandler[] = [
methodSpecificMiddleware1,
methodSpecificMiddleware2,
controller,
];
/*
Similar for other methods too:
'connect', 'delete', 'head', 'options'
'patch', 'post', 'put', 'trace'
*/
Note: Constants cannot be named as
delete
. Usedel
for HTTP method'DELETE'