Skip to content

xiaoqiang-zhao/koa-auto-path-router

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

koa-auto-path-router

中文文档

Koa auto path middleware(just for Koa 2), no need to write every router. The rule like this:

GET /a -> /GET/a/index.js

POST /a -> /POST/a/index.js

Installation

$ npm install koa-auto-path-router

API

const koa = require('koa');
const app = koa();
app.use(require('koa-auto-path-router')(root));
  • root root directory string. nothing above this root directory can be served

Example

const koaAutoPathRouter = require('koa-auto-path-router');
const Koa = require('koa');
const app = new Koa();

app.use(koaAutoPathRouter('./mock/'));

You can write the index.js like this:

module.exports = function (ctx) {
  return {
      status: 0,
      statusInfo: 'AAA',
      data: {

      }
  };
};

and there has a param "ctx", you can write like this:

module.exports = function (ctx) {
    // do something
    ctx.body = {
        status: 0,
        statusInfo: 'AAA',
        data: {
            // the query object from url
            name: ctx.query.name
        }
    };
};

if you want to do something for form data of post request, you need a package koa-bodyparser

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-auto-path-router');
var app = new Koa();
app.use(bodyParser());
app.use(router('./mock'));

get the form data like this:

module.exports = function (ctx) {
    // form data object
    ctx.request.body
};

Demo

cd demo
npm install
cd ..
npm run demo

Test

npm run test

License

MIT

About

Auto path router serving middleware for koa.

Resources

License

Stars

Watchers

Forks

Packages

No packages published