Coder Social home page Coder Social logo

tunnckocore / koa-better-router Goto Github PK

View Code? Open in Web Editor NEW
89.0 5.0 9.0 1.12 MB

:heart: Stable and lovely router for `koa`, using `path-match`. Foundation for building powerful, flexible and RESTful APIs easily.

License: MIT License

JavaScript 100.00%
router small fast composable stable extensible koa2 powerful restful middleware

koa-better-router's Introduction

koa-better-router NPM version NPM monthly downloads npm total downloads

Stable and lovely router for koa, using path-match. Foundation for building powerful, flexible and RESTful APIs easily.

standard code style linux build status coverage status dependency status

You may also be interested in koa-rest-router. It uses this router for creating powerful, flexible and RESTful APIs for enterprise easily!

Highlights

  • production: ready for and used in
  • foundation: very simple core for building more powerful routers such as koa-rest-router
  • composability: group multiple routes and multiple routers - see .groupRoutes and .addRoutes
  • flexibility: multiple prefixes on same router
  • compatibility: accepts both old and modern middlewares without deprecation messages
  • powerful: multiple routers on same koa app - even can combine multiple routers
  • light: not poluting your router instance and app - see .loadMethods
  • smart: does only what you say it to do
  • small: very small on dependencies - curated and only most needed
  • backward compatible: works on koa v1 - use .legacyMiddleware
  • maintainability: very small, beautiful, maintainable and commented codebase
  • stability: strict semantic versioning and very well documented
  • tested: very well tested with 100% coverage
  • lovely: ~500 downloads for the first 2 days
  • open: love PRs for features, issues and recipes - Contribute a recipe?

Table of Contents

(TOC generated by verb using markdown-toc)

Install

Install with npm

$ npm install koa-better-router --save

or install using yarn

$ yarn add koa-better-router

Usage

For more use-cases see the tests

let router = require('koa-better-router')().loadMethods()

// or

let Router = require('koa-better-router')
let router = Router() // or new Router(), no matter

API

Initialize KoaBetterRouter with optional options which are directly passed to path-match and so to path-to-regexp too. In addition we have two more - prefix and notFound.

Params

  • [options] {Object}: options passed to path-match/path-to-regexp directly
  • [options.notFound] {Function}: if passed, called with ctx, next when route not found

Example

let Router = require('koa-better-router')
let router = Router().loadMethods()

router.get('/', (ctx, next) => {
  ctx.body = `Hello world! Prefix: ${ctx.route.prefix}`
  return next()
})

// can use generator middlewares
router.get('/foobar', function * (next) {
  this.body = `Foo Bar Baz! ${this.route.prefix}`
  yield next
})

let api = Router({ prefix: '/api' })

// add `router`'s routes to api router
api.extend(router)

// The server
let Koa = require('koa') // Koa v2
let app = new Koa()

app.use(router.middleware())
app.use(api.middleware())

app.listen(4444, () => {
  console.log('Try out /, /foobar, /api/foobar and /api')
})

Load the HTTP verbs as methods on instance. If you not "load" them you can just use .addRoute method. If you "load" them, you will have method for each item on methods array - such as .get, .post, .put etc.

  • returns {KoaBetterRouter} this: instance for chaining

Example

let router = require('koa-better-router')()

// all are `undefined` if you
// don't `.loadMethods` them
console.log(router.get)
console.log(router.post)
console.log(router.put)
console.log(router.del)
console.log(router.addRoute) // => function
console.log(router.middleware) // => function
console.log(router.legacyMiddleware) // => function

router.loadMethods()

console.log(router.get)  // => function
console.log(router.post) // => function
console.log(router.put)  // => function
console.log(router.del)  // => function
console.log(router.addRoute) // => function
console.log(router.middleware) // => function
console.log(router.legacyMiddleware) // => function

Just creates "Route Object" without adding it to this.routes array, used by .addRoute method.

Params

  • <method> {String}: http verb or 'GET /users'
  • [route] {String|Function}: for what ctx.path handler to be called
  • ...fns {Function}: can be array or single function, any number of arguments after route can be given too
  • returns {Object}: plain route object with useful properties

Example

let router = require('koa-better-router')({ prefix: '/api' })
let route = router.createRoute('GET', '/users', [
  function (ctx, next) {},
  function (ctx, next) {},
  function (ctx, next) {},
])

console.log(route)
// => {
//   prefix: '/api',
//   route: '/users',
//   pathname: '/users',
//   path: '/api/users',
//   match: matcher function against `route.path`
//   method: 'GET',
//   middlewares: array of middlewares for this route
// }

console.log(route.match('/foobar'))    // => false
console.log(route.match('/users'))     // => false
console.log(route.match('/api/users')) // => true
console.log(route.middlewares.length)  // => 3

Powerful method to add route if you don't want to populate you router instance with dozens of methods. The method can be just HTTP verb or method plus route something like 'GET /users'. Both modern and generators middlewares can be given too, and can be combined too. Adds routes to this.routes array.

Params

  • <method> {String}: http verb or 'GET /users'
  • [route] {String|Function}: for what ctx.path handler to be called
  • ...fns {Function}: can be array or single function, any number of arguments after route can be given too
  • returns {KoaBetterRouter} this: instance for chaining

Example

let router = require('koa-better-router')()

// any number of middlewares can be given
// both modern and generator middlewares will work
router.addRoute('GET /users',
  (ctx, next) => {
    ctx.body = `first ${ctx.route.path};`
    return next()
  },
  function * (next) {
    this.body = `${this.body} prefix is ${this.route.prefix};`
    yield next
  },
  (ctx, next) => {
    ctx.body = `${ctx.body} and third middleware!`
    return next()
  }
)

// You can middlewares as array too
router.addRoute('GET', '/users/:user', [
  (ctx, next) => {
    ctx.body = `GET /users/${ctx.params.user}`
    console.log(ctx.route)
    return next()
  },
  function * (next) {
    this.body = `${this.body}, prefix is: ${this.route.prefix}`
    yield next
  }
])

// can use `koa@1` and `koa@2`, both works
let Koa = require('koa')
let app = new Koa()

app.use(router.middleware())
app.listen(4290, () => {
  console.log('Koa server start listening on port 4290')
})

Get a route by name. Name of each route is its pathname or route. For example: the name of .get('/cat/foo') route is /cat/foo, but if you pass cat/foo - it will work too.

Params

  • name {String}: name of the Route Object
  • returns {Object|Null}: Route Object, or null if not found

Example

let router = require('koa-better-router')().loadMethods()

router.get('/cat/foo', function (ctx, next) {})
router.get('/baz', function (ctx, next) {})

console.log(router.getRoute('baz'))      // => Route Object
console.log(router.getRoute('cat/foo'))  // => Route Object
console.log(router.getRoute('/cat/foo')) // => Route Object

Concats any number of arguments (arrays of route objects) to the this.routes array. Think for it like registering routes. Can be used in combination with .createRoute and .getRoute.

Params

  • ...args {Array}: any number of arguments (arrays of route objects)
  • returns {KoaBetterRouter} this: instance for chaining

Example

let router = require('koa-better-router')()

// returns Route Object
let foo = router.createRoute('GET', '/foo', function (ctx, next) {
  ctx.body = 'foobar'
  return next()
})
console.log(foo)

let baz = router.createRoute('GET', '/baz/qux', function (ctx, next) {
  ctx.body = 'baz qux'
  return next()
})
console.log(baz)

// Empty array because we just
// created them, didn't include them
// as actual routes
console.log(router.routes.length) // 0

// register them as routes
router.addRoutes(foo, baz)

console.log(router.routes.length) // 2

Simple method that just returns this.routes, which is array of route objects.

  • returns {Array}: array of route objects

Example

let router = require('koa-better-router')()

router.loadMethods()

console.log(router.routes.length) // 0
console.log(router.getRoutes().length) // 0

router.get('/foo', (ctx, next) => {})
router.get('/bar', (ctx, next) => {})

console.log(router.routes.length) // 2
console.log(router.getRoutes().length) // 2

Groups multiple "Route Objects" into one which middlewares will be these middlewares from the last "source". So let say you have dest route with 2 middlewares appended to it and the src1 route has 3 middlewares, the final (returned) route object will have these 3 middlewares from src1 not the middlewares from dest. Make sense? If not this not make sense for you, please open an issue here, so we can discuss and change it (then will change it in the koa-rest-router too, because there the things with method .groupResource are the same).

Params

  • dest {Object}: known as "Route Object"
  • src1 {Object}: second "Route Object"
  • src2 {Object}: third "Route Object"
  • returns {Object}: totally new "Route Object" using .createRoute under the hood

Example

let router = require('./index')({ prefix: '/api/v3' })

let foo = router.createRoute('GET /foo/qux/xyz', function (ctx, next) {})
let bar = router.createRoute('GET /bar', function (ctx, next) {})

let baz = router.groupRoutes(foo, bar)
console.log(baz)
// => Route Object {
//   prefix: '/api/v3',
//   path: '/api/v3/foo/qux/sas/bar',
//   pathname: '/foo/qux/sas/bar'
//   ...
// }

// Server part
let Koa = require('koa')
let app = new Koa()

router.addRoutes(baz)

app.use(router.middleware())
app.listen(2222, () => {
  console.log('Server listening on http://localhost:2222')

  router.getRoutes().forEach((route) => {
    console.log(`${route.method} http://localhost:2222${route.path}`)
  })
})

Extends current router with routes from router. This router should be an instance of KoaBetterRouter too. That is the correct extending/grouping of couple of routers.

Params

  • <router> {Object}: instance of KoaBetterRouter
  • returns {KoaBetterRouter} this: instance for chaining

Example

let router = require('koa-better-router')()
let api = require('koa-better-router')({
  prefix: '/api/v4'
})

router.addRoute('GET', '/foo/bar', () => {})
router.addRoute('GET', '/api/v4/qux', () => {}) // intentional !
api.addRoute('GET', '/woohoo')

api.extend(router)

api.getRoutes().forEach(route => console.log(route.path))
// => outputs (the last one is expected)
// /api/v4/woohoo
// /api/v4/foo/bar
// /api/v4/api/v4/qux

Active all routes that are defined. You can pass opts to pass different prefix for your routes. So you can have multiple prefixes with multiple routes using just one single router. You can also use multiple router instances. Pass legacy: true to opts and you will get generator function that can be used in Koa v1.

  • returns {Function}: modern koa v2 middleware

Example

let Router = require('koa-better-router')
let api = Router({ prefix: '/api' })

api.loadMethods()
  .get('GET /', (ctx, next) => {
    ctx.body = 'Hello world!'
    return next()
  }, (ctx, next) => {
    ctx.body = `${ctx.body} Try out /api/users too`
    return next()
  })

api.get('/users', function * (next) {
  this.body = `Prefix: ${this.route.prefix}, path: ${this.route.path}`
  yield next
})

// Server part
let Koa = require('koa')
let app = new Koa()

// Register the router as Koa middleware
app.use(api.middleware())

app.listen(4321, () => {
  console.log('Modern Koa v2 server is started on port 4321')
})

Explicitly use this method when want to use the router on Koa@1, otherwise use .middleware method!

  • returns {GeneratorFunction}: old koa v1 middleware

Example

let app = require('koa')() // koa v1.x
let router = require('koa-better-router')()

router.addRoute('GET', '/users', function * (next) {
  this.body = 'Legacy KOA!'
  yield next
})

app.use(router.legacyMiddleware())
app.listen(3333, () => {
  console.log('Open http://localhost:3333/users')
})

Related

  • koa-bel: View engine for koa without any deps, built to be used with bel. Any other engines that can be writtenโ€ฆ more | homepage
  • koa-better-body: Full-featured koa body parser! Support parsing text, buffer, json, json patch, json api, csp-report, multipart, form and urlencoded bodies. Worksโ€ฆ more | homepage
  • koa-better-ratelimit: Better, smaller, faster - koa middleware for limit request by ip, store in-memory. | homepage
  • koa-better-serve: Small, simple and correct serving of files, using koa-send - nothing more. | homepage
  • koa-ip-filter: Middleware for koa that filters IPs against glob patterns, RegExp, string or array of globs. Support custom 403 Forbidden messageโ€ฆ more | homepage
  • koa-rest-router: Most powerful, flexible and composable router for building enterprise RESTful APIs easily! | homepage
  • nanomatch: Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (noโ€ฆ more | homepage

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Please read the contributing guidelines for advice on opening issues, pull requests, and coding standards.
If you need some help and can spent some cash, feel free to contact me at CodeMentor.io too.

In short: If you want to contribute to that project, please follow these things

  1. Please DO NOT edit README.md, CHANGELOG.md and .verb.md files. See "Building docs" section.
  2. Ensure anything is okey by installing the dependencies and run the tests. See "Running tests" section.
  3. Always use npm run commit to commit changes instead of git commit, because it is interactive and user-friendly. It uses commitizen behind the scenes, which follows Conventional Changelog idealogy.
  4. Do NOT bump the version in package.json. For that we use npm run release, which is standard-version and follows Conventional Changelog idealogy.

Thanks a lot! :)

Contributing Recipes

Recipes are just different use cases, written in form of README in human language. Showing some "Pro Tips" and tricks, answering common questions and so on. They look like tests, but in more readable and understandable way for humans - mostly for beginners that not reads or understand enough the README or API and tests.

  • They are in form of folders in the root recipes/ folder: for example recipes/[short-meaningful-recipe-name]/.
  • In recipe folder should exist README.md file
  • In recipe folder there may have actual js files, too. And should be working.
  • The examples from the recipe README.md should also exist as separate .js files.
  • Examples in recipe folder also should be working and actual.

It would be great if you follow these steps when you want to fix, update or create a recipes. ๐Ÿ˜Ž

  • Title for recipe idea should start with [recipe]: for example[recipe] my awesome recipe
  • Title for new recipe (PR) should also start with [recipe].
  • Titles of Pull Requests or Issues for fixing/updating some existing recipes should start with [recipe-fix].

It will help a lot, thanks in advance! ๐Ÿ˜‹

Building docs

Documentation and that readme is generated using verb-generate-readme, which is a verb generator, so you need to install both of them and then run verb command like that

$ npm install verbose/verb#dev verb-generate-readme --global && verb

Please don't edit the README directly. Any changes to the readme must be made in .verb.md.

Running tests

Clone repository and run the following in that cloned directory

$ npm install && npm test

Author

Charlike Mike Reagent

License

Copyright ยฉ 2016-2017, Charlike Mike Reagent. Released under the MIT license.


This file was generated by verb-generate-readme, v0.4.1, on January 20, 2017.
Project scaffolded using charlike cli.

koa-better-router's People

Contributors

doumanash avatar joebartels avatar renovate-bot avatar tunnckocore avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

koa-better-router's Issues

how can i use promise and await?

how can I use Promise in router function like this?

router.post('/user', body(), function * (next) {
  let p=new Promise()
  p.then(()=>{//do something then next})
  .catch((err)=>{//do something then next})
})

appreciate for any help.

add `.createRoute` method

For easier creating Route Objects. Same as .addRoute but without the pushing to this.routes.

ps: I need it in koa-rest-router

semver-minor v1.1.0

Weekly Digest (3 March, 2019 - 10 March, 2019)

Here's the Weekly Digest for tunnckoCoreLabs/koa-better-router:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were no stargazers.


RELEASES

Last week there were no releases.


That's all for last week, please ๐Ÿ‘€ Watch and โญ Star the repository tunnckoCoreLabs/koa-better-router to receive next weekly updates. ๐Ÿ˜ƒ

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. ๐Ÿ“†

allow to be used in express.js

Not so big and hard thing to be done. Will have new method, for example .expressMiddleware. And we need a better "express compose". Some work is done in compose-middleware, but don't think it is okey... and.. doh it is written in TypeScript - why?

Nevermind. So I'll create express-better-compose first.

Use a middleware on a SINGLE route?

I expected to have each matching route be called, but only the FIRST one gets triggered/checked for `http://domain.tld/'

// filter middleware
let isBlogDomain = async (ctx, next) => {
	if (ctx.host.indexOf('blog') !== -1)
		await next();
};

// blog.domain.tld
router.get('/test/', [   isBlogDomain,  // <- the filtering middleware
	async (ctx, next) => {
		ctx.body ="BLOG";
}]);

// domain.tld
router.get('/test/', [ 
	async (ctx, next) => {
		ctx.body ="Default";
}]);

my first test on this, using localhost:8080/test1/x -> will fall through and return "Not Found":

router.get('/test1/:key',
	[
		async (ctx, next) => {
			if (ctx.params.key[0] == 'a')
				ctx.body = 'a';
			else
				next();
		},

		async (ctx, next) => {
			if (ctx.params.key[0] == 'b')
				ctx.body = 'b';
			else
				next();
		}
	]
);

router.get('/test1/:key',
	[
		async (ctx, next) => {
			if (ctx.params.key[0] == 'x')
				ctx.body = 'x';
			else
				next();
		},

		async (ctx, next) => {
			if (ctx.params.key[0] == 'y')
				ctx.body = 'y';
			else
				next();
		}
	]
);

Weekly Digest (12 May, 2019 - 19 May, 2019)

Here's the Weekly Digest for tunnckoCoreLabs/koa-better-router:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were no stargazers.


RELEASES

Last week there were no releases.


That's all for last week, please ๐Ÿ‘€ Watch and โญ Star the repository tunnckoCoreLabs/koa-better-router to receive next weekly updates. ๐Ÿ˜ƒ

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. ๐Ÿ“†

Weekly Digest (10 February, 2019 - 17 February, 2019)

Here's the Weekly Digest for tunnckoCoreLabs/koa-better-router:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were no stargazers.


RELEASES

Last week there were no releases.


That's all for last week, please ๐Ÿ‘€ Watch and โญ Star the repository tunnckoCoreLabs/koa-better-router to receive next weekly updates. ๐Ÿ˜ƒ

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. ๐Ÿ“†

Weekly Digest (5 May, 2019 - 12 May, 2019)

Here's the Weekly Digest for tunnckoCoreLabs/koa-better-router:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were no stargazers.


RELEASES

Last week there were no releases.


That's all for last week, please ๐Ÿ‘€ Watch and โญ Star the repository tunnckoCoreLabs/koa-better-router to receive next weekly updates. ๐Ÿ˜ƒ

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. ๐Ÿ“†

add `.groupRoutes` method?

Seems reasonable. And it may be useful. So later in koa-rest-router we will have

For route

  • addRoute
  • createRoute

For routes

  • addRoutes
  • getRoutes
  • groupRoutes

For single resource

  • resource
  • addResource
  • getResource
  • createResource

For resources

  • addResources
  • getResources
  • groupResources

semver-minor v1.2.0

Middleware does not stop on successful match

When koa-better-router successfully matches a URL to a route and runs the handler, it doesn't stop and continues through Koa middleware stack. This is unlike what probably every other router (including koa-router) does.

Compare two examples:

const Koa = require('koa')
const Router = require('koa-better-router')

const router = Router({prefix: '/api'})
router.addRoute('GET', '/', ctx => {
  console.log('api called')
  ctx.body = 'api called'
})

const app = new Koa()
app.use(router.middleware())
app.use(ctx => {
	ctx.body = 'Nothing here, mate.'
})

app.listen(3000)

// curl localhost:3000/api -> Nothing here, mate. (console.log called!)
// curl localhost:3000/boo -> Nothing here, mate.

Now the same example with koa-router will work as expected:

const Koa = require('koa')
const Router = require('koa-router')

const router = Router({prefix: '/api'})
router.get('/', ctx => {
  ctx.body = 'api called'
})

const app = new Koa()
app.use(router.routes()).use(router.allowedMethods())
app.use(ctx => {
	ctx.body = 'Nothing here, mate.'
})

app.listen(3000)

// curl localhost:3000/api -> api called
// curl localhost:3000/boo -> Nothing here, mate.

Please explain what am I missing? How do I stop propagation with koa-better-router (and koa-rest-router), and what's the rationale of NOT doing that by default?

Weekly Digest (17 February, 2019 - 24 February, 2019)

Here's the Weekly Digest for tunnckoCoreLabs/koa-better-router:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were no stargazers.


RELEASES

Last week there were no releases.


That's all for last week, please ๐Ÿ‘€ Watch and โญ Star the repository tunnckoCoreLabs/koa-better-router to receive next weekly updates. ๐Ÿ˜ƒ

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. ๐Ÿ“†

Should there be a way to set a default route? (not found)

While looking into code i found that regardless if route is found or not, next middleware is called. So you cannot exactly be sure without examining koa context wether route is matched or not.

What do you think about adding possibility of configuring default router(i.e. 404 router)?

How to enforce authentication for all routes under prefix?

@tunnckoCore first I wanted to say thanks a lot for writing this library and very thorough documentation! I'm new to Koa, and this has been very helpful.

I've been fiddling with a side project, and I was trying to determine the best way to ensure that a router with a prefix (or any router I suppose) enforces a condition to be met, like authentication.

For example, I have a router, const router = require('koa-better-router')({ prefix: '/app' }).loadMethods();

and several routes:

// /app/home
router.get('/home', async (ctx, next) => { ... });
// /app/foo
router.get('/foo', async (ctx, next) => { ... });
// /app/bar
router.get('/bar', async (ctx, next) => { ... });

I could put a check in each route like so:

router.get('/home', async (ctx, next) => {
    if (!authenticated) {
        ctx.redirect('/login');
    } else {
        ctx.render('..', {});
    }
    return next();
});

but this is very repetitive. I believe I could wrap that check in a function, but it's still somewhat repetitive, as I would have to add that function to each route.

Is there an existing simpler approach to ensure all the routes for a given router meet a condition?

Please let me know if I can clarify anything.

Use middleware on every route in a router

Hi ๐Ÿ‘‹!

Is there any way to apply a middleware to every route of a router?
This would be the same as calling Router.use without a path in koa-router.

const Router = require('koa-router')
const router = new Router({ prefix: '/users' })

// both GET /users and GET /users/:user will call the secure middleware
router.use(secure)

router.get('/', async (ctx) => {
  ctx.response.body = await User.getAll()
})

router.get('/:user', async (ctx) => {
  ctx.response.body = await User.get(ctx.params.user)
})

Thanks.

Getting the "matched" route without actual routing?

Is it possible to match for a route or get the matched route before doing the actual routing?

The use case would be for things like authentication middleware.

So you could have a top middleware determining which route is going to be routed to, then you have one below which could allow/deny. Then you actually route.

This way individual routes wouldn't have to worry about authentication (like forgetting to protect them with a middleware at the time of creation).

Without "match without routing" you'd have to string match the URL manually.

Dependency deprecation warning: bel (npm)

On registry https://registry.npmjs.org/, the "latest" version (v6.0.0) of dependency bel has the following deprecation notice:

Renamed to 'nanohtml'. 'npm install nanohtml'

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about bel's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

remove `.legacyMiddleware`

Make .middleware smart enough to understand on what koa is used.

It could be arguments.length === 2 && typeof ctx === function && typeof !== 'object' or something similar

addRoutes() adds unusable router and extend() will loose all prefixes

Adding a let r2 = new Router({prefix: 'a'}).loadMethods().get('/', (ctx, next) => {ctx.body='supposed to be at /api/a/'; return next();}) with let r1 = new Router({prefix: 'api'}).addRoutes(r2); does not result in a callable route. Actually koa-better-router crashes with not having any routes.

And using extend -> let r1 = new Router({prefix: 'api'}).extend(r2); will loose all prefix info from r2. Putting all '/' routes at the same base level.

Any known workaround?

notFound option does not respect router prefix

notFound option does not respect router prefix.

It is called for any non-matched path, regardless of the prefix, meaning it can't be used if there are several routers under different prefixes.

Example:

const Koa = require('koa')
const Router = require('koa-better-router')

const router1 = new Router({
	prefix: '/api/v1',
	notFound: (ctx, next) => {
		ctx.status = 404
		next()
	}
})
router1.addRoute('GET /foo', ctx => {
	ctx.body = 'foo1'
})

const router2 = new Router({prefix: '/api/v2'})
router2.addRoute('GET /foo', ctx => {
	ctx.body = 'foo2'
})

const app = new Koa()
app.use(router1.middleware())
app.use(router2.middleware())
app.listen(3000)

Then call it:

$ curl localhost:3000/api/v2/foo -v
> GET /api/v2/foo HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 404 Not Found
< Content-Type: text/plain; charset=utf-8
< Content-Length: 4
< Date: Thu, 03 Aug 2017 06:33:21 GMT
< Connection: keep-alive
<
foo2

Expected reply: HTTP 200 OK.

v1.2

  • add .addRoutes (moved from koa-rest-router)
  • add .getRoute (inspired by koa-rest-router's getResource/getResources)
  • add .getRoutes (moved from koa-rest-router)
  • add .groupRoutes #3
  • working examples/recipes #4
  • contributing guide for recipes
  • features and WHYs section #4

Weekly Digest (28 April, 2019 - 5 May, 2019)

Here's the Weekly Digest for tunnckoCoreLabs/koa-better-router:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 2 stagazers.
โญ posquit0
โญ tzaeru
You all are the stars! ๐ŸŒŸ


RELEASES

Last week there were no releases.


That's all for last week, please ๐Ÿ‘€ Watch and โญ Star the repository tunnckoCoreLabs/koa-better-router to receive next weekly updates. ๐Ÿ˜ƒ

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. ๐Ÿ“†

Weekly Digest (8 February, 2019 - 15 February, 2019)

Here's the Weekly Digest for tunnckoCoreLabs/koa-better-router:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were no stargazers.


RELEASES

Last week there were no releases.


That's all for last week, please ๐Ÿ‘€ Watch and โญ Star the repository tunnckoCoreLabs/koa-better-router to receive next weekly updates. ๐Ÿ˜ƒ

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. ๐Ÿ“†

Weekly Digest (24 February, 2019 - 3 March, 2019)

Here's the Weekly Digest for tunnckoCoreLabs/koa-better-router:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were no stargazers.


RELEASES

Last week there were no releases.


That's all for last week, please ๐Ÿ‘€ Watch and โญ Star the repository tunnckoCoreLabs/koa-better-router to receive next weekly updates. ๐Ÿ˜ƒ

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. ๐Ÿ“†

Router.extend does not take into account the prefix of the argument router.

version: 2.1.1
description:

Create router with prefix and add it to another router (extend):

let Router = require('koa-better-router');

const mailRouter = new Router({
    prefix: "/mail"
}).loadMethods();
mailRouter.get('/a', function * (next) {});
mailRouter.get('/b', function * (next) {});

const router = Router();
router.extend(mailRouter);

router.getRoutes().forEach((route) => {
    console.log(`- ${route.path} [${route.method}]`);
});

What I expect:

- /mail/a [GET]
- /mail/b [GET]

What I got:

- /a [GET]
- /b [GET]

I consider that it is necessary to add prefix to extended routes.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.