express-file-router-2
v1.0.2
Published
An express router that allows you to use the file system to create routes.
Downloads
3
Maintainers
Readme
express-file-router
Installation
npm install express-file-router
How to Use
You can integrate the file router by using it as a middleware like this:
app.use(
"/api",
await FileRouter(
{
ROUTES_DIR: "/routes", // directory of your routes
debug: true, // simple console.log's
},
__dirname
)
);
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import { createServer } from "http";
import FileRouter from "express-file-router-2";
async function init(): Promise<void> {
process.on("uncaughtException", (err) => {
console.log(err);
});
const app = express();
app.use(cors());
app.use(
bodyParser.json({
limit: "50mb",
})
);
app.use(bodyParser.urlencoded({ extended: true, limit: "50mb" }));
app.use(
"/api",
await FileRouter(
{
ROUTES_DIR: "/routes",
debug: true,
},
__dirname
)
);
const server = createServer(app);
const port = 3080;
server.listen(port, () => console.log(`Server listening on port ${port}`));
}
init();
Route Setup
Example Structure
├── index.ts // main file
├── routes
├── get.ts // get
├── dynamic // params
├── param
├── [example].ts // single
└── [...slug].ts // get all
└── post.ts // post
Middleware
You are able to add route specific middlewares by exporting an array like this:
Post Example
import { RequestHandler } from "express";
import UserSession from "@/middleware/session/user";
export const post = [
// inside of file
async (req, res, next) => {
console.log("headers", req.headers);
return next();
},
// imported middelware from file
UserSession,
async (req, res) => {
const { userID } = req.params;
console.log("req.params", req.params);
return res.status(200).json({
message: "Success",
userID,
});
},
] as RequestHandler[];
Get Example
import { RequestHandler } from "express";
import UserSession from "@/middleware/session/user";
export const get = [
// inside of file
async (req, res, next) => {
console.log("headers", req.headers);
return next();
},
// imported middelware from file
UserSession,
async (req, res) => {
const { userID } = req.params;
console.log("req.params", req.params);
return res.status(200).json({
message: "Success",
userID,
});
},
] as RequestHandler[];