npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

moa-router

v1.7.9

Published

a better && faster router base on find-my-way(support koa/express/http).find-my-way is a Crazy fast http radix based router

Downloads

12

Readme

moa-router

a better && faster router base on find-my-way(support koa/express/http)

js-standard-style Build Status Coverage Status NPM downloads

A crazy fast HTTP router, internally uses an highly performant Radix Tree (aka compact Prefix Tree), supports route params, wildcards, and it's framework independent.

If you want to see a benchmark comparison with the most commonly used routers, see here.
Do you need a real-world example that uses this router? Check out Fastify.

Performace

$ autocannon 127.0.0.1:3000/test

QPS

  1. moa-router(http) 28456
  2. moa-router(koa) 17439.6
  3. koa-router 12748.73
  4. moa-router(express) 11779.1
  5. express-router 10374.6

Install

$ npm i --save moa-router

Usage

Koa

const http = require('http')
const Koa = require('koa');
const app = new Koa();

const router = require('moa-router')()

router.get('/', (ctx, next) => {
  ctx.body = {'path': 'root'}
})

router.on('GET', '/test', (ctx, next) => {
  ctx.body = {'hello': 'world'}
})

app.use(router.routes());

app.use(async function (ctx, next) {
  ctx.body = "default"
});

const server = http.createServer(app.callback())

server.listen(3030, err => {
  if (err) throw err
  console.log('Server listening on: http://localhost:3000')
})

Express

const http = require('http')
const express = require('express')
const app = express()

const router = require('moa-router')()
router.type = 'express'

router.get('/', (req, res, next) => {
  res.json({'path': 'root'}) 
})

router.on('GET', '/test', (req, res, next) => {
  res.json({'hello': 'world'})
})

app.use(router.routes())

app.use(async function (ctx, next) {
  res.send("default")
})

const server = http.createServer(app)

server.listen(3000, err => {
  if (err) throw err
  console.log('Server listening on: http://localhost:3000')
})

HTTP(fastify)

'use strict'

const http = require('http')
const router = require('moa-router')()
router.type = 'http'

router.on('GET', '/test', (req, res, params) => {
  res.end('{"hello":"world"}')
})

const server = http.createServer(router.routes())

server.listen(3000, err => {
  if (err) throw err
  console.log('Server listening on: http://localhost:3000')
})

API

FindMyway([options])

Instance a new router.
You can pass a default route with the option defaultRoute.

const router = require('moa-router')({
  defaultRoute: (ctx, next) => {
    ctx.status = 404
  }
})

on(method, path, handler, [store])

Register a new route.

router.on('GET', '/example', (ctx, next) => {
  // your koa code
})

Last argument, store is used to pass an object that you can access later inside the handler function. If needed, store can be updated.

router.on('GET', '/example', (ctx, next) => {
  assert.equal(ctx.store, { message: 'hello world' })
}, { message: 'hello world' })
on(methods[], path, handler, [store])

Register a new route for each method specified in the methods array. It comes handy when you need to declare multiple routes with the same handler but different methods.

router.on(['GET', 'POST'], '/example', (ctx, next) => {
  // your code
})

Supported path formats

To register a parametric path, use the colon before the parameter name. For wildcard use the star. Remember that static routes are always inserted before parametric and wildcard.

// parametric
router.on('GET', '/example/:userId', (ctx, next) => {}))
router.on('GET', '/example/:userId/:secretToken', (ctx, next) => {}))

// wildcard
router.on('GET', '/example/*', (ctx, next) => {}))

Regular expression routes are supported as well, but pay attention, RegExp are very expensive in term of performance!

// parametric with regexp
router.on('GET', '/example/:file(^\\d+).png', () => {}))

It's possible to define more than one parameter within the same couple of slash ("/"). Such as:

router.on('GET', '/example/near/:lat-:lng/radius/:r', (ctx, next) => {}))

Remember in this case to use the dash ("-") as parameters separator.

Finally it's possible to have multiple parameters with RegExp.

router.on('GET', '/example/at/:hour(^\\d{2})h:minute(^\\d{2})m', (ctx, next) => {}))

In this case as parameter separator it's possible to use whatever character is not matched by the regular expression.

Having a route with multiple parameters may affect negatively the performance, so prefer single parameter approach whenever possible, especially on routes which are on the hot path of your application.

Match order

The routes are matched in the following order:

static
parametric
wildcards
parametric(regex)
multi parametric(regex)
Caveats
  • Since static routes have greater priority than parametric routes, when you register a static route and a dynamic route, which have part of their path equal, the static route shadows the parametric route, that becomes not accessible. For example:
const assert = require('assert')
const router = require('moa-router')({
  defaultRoute: (ctx, next) => {
    assert(ctx.req.url === '/example/shared/nested/oops')
  }
})

router.on('GET', '/example/shared/nested/test', (ctx, next) => {
  assert.fail('We should not be here')
})

router.on('GET', '/example/:param/nested/oops', (ctx, next) => {
  assert.fail('We should not be here')
})

router.lookup({ method: 'GET', url: '/example/shared/nested/oops' }, null)
  • It's not possible to register two routes which differs only for their parameters, because internally they would be seen as the same route. In a such case you'll get an early error during the route registration phase. An example is worth thousand words:
const findMyWay = FindMyWay({
  defaultRoute: (ctx, next) => {}
})

findMyWay.on('GET', '/user/:userId(^\\d+)', (ctx, next) => {})

findMyWay.on('GET', '/user/:username(^[a-z]+)', (ctx, next) => {})
// Method 'GET' already declared for route ':'

Shorthand methods

If you want an even nicer api, you can also use the shorthand methods to declare your routes.

router.get(path, handler [, store])
router.delete(path, handler [, store])
router.head(path, handler [, store])
router.patch(path, handler [, store])
router.post(path, handler [, store])
router.put(path, handler [, store])
router.options(path, handler [, store])
router.trace(path, handler [, store])
router.connect(path, handler [, store])

If you need a route that supports all methods you can use the all api.

router.all(path, handler [, store])

lookup(ctx, next)

Start a new search, ctx and next are the server ctx.req/ctx.res objects.
If a route is found it will automatically called the handler, otherwise the default route will be called.
The url is sanitized internally, all the parameters and wildcards are decoded automatically.

router.lookup(ctx, next)

find(method, path)

Return (if present) the route registered in method:path.
The path must be sanitized, all the parameters and wildcards are decoded automatically.

router.find('GET', '/example')
// => { handler: Function, params: Object, store: Object}
// => null

prettyPrint()

Prints the representation of the internal radix tree, useful for debugging.

findMyWay.on('GET', '/test', () => {})
findMyWay.on('GET', '/test/hello', () => {})
findMyWay.on('GET', '/hello/world', () => {})

console.log(findMyWay.prettyPrint())
// └── /
//   ├── test (GET)
//   │   └── /hello (GET)
//   └── hello/world (GET)

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

版本历史

  • v1.0.0 初始化版本

欢迎fork和反馈

如有建议或意见,请在issue提问或邮件

License

find-my-way - MIT
trekjs/router - MIT

this repo is released under the MIT License. Copyright © 2017 i5ting