1.0.5 • Published 3 years ago

express-autoload-router v1.0.5

Weekly downloads
2
License
MIT
Repository
github
Last release
3 years ago

express-autoload-router

Load routers from specific folders for Express.js

NPM version npm download David deps

中文文档

Install

npm i express-autoload-router -S

Usage

const path = require('path');
const express = require('express');
const loadRouter = require('express-autoload-router');

const app = express();

// Use `path.join(__dirname, 'path/to/folder')` here
loadRouter(app, '/api', path.join(__dirname, 'controllers'));

Notice

controller filename must end with '_controller.js', like: list_controller.js api function name must endwith 'Action', like: apiAction

Options

loadRouter(app, '/api', path.join(__dirname, 'controllers'));

access url: http://127.0.0.1:4000/api/product/detail

Controller declaration

There are three kinds of Controller for this package:

  • Plain function
exports.apiAction = (req, res) => {
  res.send('API');
};
  • Object
PropertyTypeRequiredDefaultNote
methodString AarryNoGETone of 'GET', 'POST', 'PUT', 'DELETE'
middlewaresArrayNo[]Array of middlewares, see below
handlerFunctionYes--

e.g.

exports.apiAcion = {
  method: ['GET'],
  params: [':id'],
  handler(req, res) {
    res.send('API');
  }
};

Middlewares support

This package also support middlewares in controller.

e.g.

exports.api = {
  method: ['GET'],
  middlewares: [
    function (req, res, next) {
      console.log('Middleware 1');
      next();
    },
    function (req, res, next) {
      console.log('Middleware 2');
      next();
    },
  ],
  handler(req, res) {
    return res.send(`product detail ${req.params.id}`);
  },
};

Example

See example.

License

The MIT License

1.0.5

3 years ago

1.0.4

5 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago