Skip to content

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Express Route Loader

Automatically load route handlers from script files, catch errors and map the function name to the URL path.

function getArticles() {
} // becomes HTTP GET /articles 🙌

Test NPM

Get Started

Installation

# Install the package via NPM:
npm install --save @dobschal/express-route-loader

Import

// ES6
import {routeLoader} from "@dobschal/express-route-loader";

// CommonJS
const {routeLoader} = require("@dobschal/express-route-loader");

Use

// Expect to have all route handlers in routes/
app.use(routeLoader(path.join(__dirname, "routes")));

Router Handler

// Will add GET /users route handler
export function getUsers() {
    // ...
    return users;
}

Example

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});
}

Auto Response

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()};
}

Error Handling

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.");
    }
}

Prefixes

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
}

About

🪄 Auto load route handlers in Express JS applications.

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages