Automatically load route handlers from script files, catch errors and map the function name to the URL path.
function getArticles() {
} // becomes HTTP GET /articles 🙌
# Install the package via NPM:
npm install --save @dobschal/express-route-loader
// ES6
import {routeLoader} from "@dobschal/express-route-loader";
// CommonJS
const {routeLoader} = require("@dobschal/express-route-loader");
// Expect to have all route handlers in routes/
app.use(routeLoader(path.join(__dirname, "routes")));
// Will add GET /users route handler
export function getUsers() {
// ...
return users;
}
app.js
import express from "express";
import path from "path";
import {routeLoader} from "@dobschal/express-route-loader";
// Instantiate express app and configure...
const app = express();
// Apply auto loader
app.use(routeLoader(path.join(__dirname, "routes")));
app.listen(/* ... */);
routes/user.js
// This will apply as route handler for GET /users
export async function getUsers(body, req, res) {
const users = await loadUsers();
res.send({users});
}
Instead of calling res.send(/* ... */)
you can use the return keyword to send a JSON HTTP response.
export async function getUsers() {
return {users: await loadUsers()};
}
If an error is thrown inside a route handler, the error is automatically forwarded to the Express Error Handler via the NextFunction.
export function postLogin({password}) {
// This will automatically be caught
// Just implement a global ExpressJS Error Handler
if (passwordIsWrong(password)) {
throw new Error("Password is wrong.");
}
}
You can add a prefix to each route by exporting a prefix
string variable.
export const prefix = "/api/v1";
export function getUsers() { // Will be GET /api/v1/users
}