2.1.1 • Published 3 years ago

fs-express-router v2.1.1

Weekly downloads
-
License
GPL-2.0
Repository
github
Last release
3 years ago

fs-express-router

Simple File System Routing for ExpressJS, inspired by NuxtJS's router.

version npm issues stars

Getting Started

Install fs-express-router as a dependency:

$ npm i fs-express-router

Add the router to your existing Express app:

// src/index.js
const { createRouter } = require('fs-express-router');
const path = require('path');

const routerOpts = {
  // point to your routes directory
  baseDir: path.join(__dirname, 'routes'),
};

const router = createRouter(routerOpts);
app.use('/', router);

Directory Structure

fs-express-router reads all files inside your routes (or wherever you point it to) directory, and builds the route based on the file's path and applies the exported verb (const get, post, put, // etc...) as the handlers.

Router Config

FieldTypeDescriptionDefault
baseDirstringChange the base directory to include. Path must be absolute./routes
strictExportsbooleanThrow an error if a file exports an unknown variable.false
routerobjectOptions to pass to Express router.undefined
middlewaresfunction\|arrayMiddlewares to add to all router's routes.undefined
dirsarrayA string or regex array to test for allowed directories.undefined
excludeDirsarrayA string or regex array to test for excluded directories.undefined
includeRootFilesbooleanInclude files inside the root directory.true

Sample Routes

├── routes/
│   ├── users/
│   │   └── _id/
│   │       ├── index.js
│   │       └── data.js
│   └── index.js

Sample Handlers

Important: delete method is aliased as del, since delete is a reserved keyword.

// src/routes/index.js
// GET /
const get = (req, res) => {
  res.json({ message: 'Hello world!' });
}

module.exports = { get };
// src/routes/users/_id/index.js
// GET /users/:id
const get = (req, res) => {
  res.json({ userId: req.params.id });
}

// DELETE /users/:id
const del = (req, res) => {
  res.json({ userId: req.params.id, deleted: 1 });
}

module.exports = { get, del };
// src/routes/users/_id/data.js
// GET /users/:id/data
const get = (req, res) => {
  res.json({ userId: req.params.id, name: 'foo' });
}

// POST /users/:id/data
const post = (req, res) => {
  res.json({ userId: req.params.id, ok: 1 });
}

module.exports = { get, post };

Middlewares

fs-express-router grabs middlewares from an exported variable middlewares.

Usage

// Per-router middleware
const { createRouter } = require('fs-express-router');

const middlewares;
const router = createRouter({ middlewares });

// Per-file middleware
const middlewares;
module.exports = { middlewares };

Per-file middlewares

// single middleware
const middlewares = async (req, res, next) => {
  console.log('this route was called!');
  next();
};

// multiple middlewares
const middlewares = [
  myMiddleware1,
  myMiddleware2,
];

Per-handler middlewares

// single/multiple middlewares
const middlewares = {
  async get(req, res, next) {
    console.log('get handler was called!');
    next();
  },
  post: [myAuthMiddleware, async (req, res, next) => {
    console.log('post handler authenticated!')
    next();
  }],
}

Advanced Usage

Router composition

You can include/exclude directories with each router, allowing you to easily compose multiple routes with custom middlewares.

const { Router } = require('express');
const { createRouter } = require('fs-express-router');

// Base router where we attach our actual routes
const baseRouter = Router();

// Router where we add auth middlewares
const authRouter = createRouter({
  // Only add routes inside /routes/auth/*
  includeDirs: ['auth'],
  // Attach our auth middlewares
  middlewares: async (req, res, next) => {
    // do authentication
    console.log('request authenticated!');
    next();
  },
});

// Router where any requests can go through
const publicRouter = createRouter({
  // Exclude our authenticated routes
  excludeDirs: ['auth'],
  // Optional: only enable if you have files like /routes/index.js
  includeRootFiles: true,
});

// Attach our routers to our base router
baseRouter.use(authRouter);
baseRouter.use(publicRouter);

// Use our router
app.use('/api', baseRouter);

Typescript

This package is written using Typescript, so types are supported out of the box!

// Interfaces
import { Middlewares, RouterOpts } from 'fs-express-router';

const middlewares: Middlewares = [];
const routerOpts: RouterOpts = {};

// Handlers
import { RequestHandler } from 'express';
import { Middlewares } from 'fs-express-router';

export const middleware: Middlewares = {
  async get(req, res, next) {
  }
}

export const get: RequestHandler = async (req, res, next) => {
};
2.1.1

3 years ago

2.1.0

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.1.4

3 years ago

1.1.3

3 years ago

1.1.2

3 years ago

1.1.1

3 years ago

1.0.0

3 years ago