New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

url-router

Package Overview
Dependencies
Maintainers
1
Versions
46
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

url-router

A non-opinionated cross-platform URL routing library.

  • 7.0.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
688
decreased by-11.11%
Maintainers
1
Weekly downloads
 
Created
Source

url-router

A non-opinionated cross-platform URL routing library.

Installing

npm install url-router

Examples

Browser:

import Router from 'url-router'

const router = new Router([
  ['/', () => import('./views/Homepage')],
  ['/user/:id/profile', () => import('./views/UserProfile')],
  [/^\/article\/(\d+)$/, () => import('./views/Article')],

  // es2018 named capture groups
  [/^\/post\/(?<id>\d+)$/, () => import('./views/Post')]
])

const route = router.find(location.pathname)
route.handler(route)

node.js:

const http = require('http')
const Router = require('url-router')
const { URL } = require('url')

const article = require('./controllers/article')

const router = new Router([
  ['GET','/article/:id', article.get],
  ['POST', '/article', article.create],
  ['PUT', '/article/:id', article.update],
  ['DELETE', '/article/:id', article.remove],
])

http.createServer((req, res) => {
  const url = new URL(req.url)
  const route = router.find(req.method, url.pathname)
  route.handler({ req, res, route })
}).listen(8080)

API

new Router(routes)

Creates a router instance.

Params:
routes: Array. An array of routes.

route signature:

new Router([
  [method?, path, handler, test?],
  ...
])
method

String. Optional. HTTP method. GET, POST, PUT, DELETE, HEAD, CONNECT, OPTIONS, TRACE, PATCH.
If method is omitted, it defaults to GET.

path

String | Regexp. The path to match against the request path.

You could define route params in path, for example:

const router = new Router([
  ['/people/:username/articles/:articleId', handler]
])

router.find('/people/johnsmith/articles/123')

/*
result:
{
  method: 'GET',
  path: '/people/johnsmith/articles/123',
  handler: handler
  params: { username: 'johnsmith', articleId: '123' }
}
*/

* is wildcard, e.g., route path /foo*bar can match /foowwsdfbar.

If you need more power, use Regexp. Capture groups will be set as route params, keys are $1, $2, ....

const router = new Router([
  [/^\/article\/(\d+)$/, handler]
])

router.find('/article/123')

/*
result:
{
  method: 'GET',
  path: '/article/123',
  handler: handler
  params: { $1: '123' }
}
*/

You can use named capture groups introduced in ES2018:

const router = new Router([
  [/^\/article\/(?<id>\d+)$/, handler]
])

router.find('/article/123')

/*
result:
{
  method: 'GET',
  path: '/article/123',
  handler: handler
  params: { id: '123' }
}
*/
handler

Any type. The handler you wish to handle the request. Based on your framework design, the handler can be a function to handle the request, or the file path to your controller file, or an object (such as Vue component), etc.

If handler is a string and contains $ character, and path is a regexp (string with route params and wildcard will be converted to regexp underlying), the handler will be rewitten. For example:

const router = new Router([
  ['/people/:username/:page', '/people/$2']
])

router.find('/people/johnsmith/articles')

/*
result:
{
  method: 'GET',
  path: '/people/johnsmith/articles',
  handler: '/people/articles',
  params: { username: 'johnsmith', page: 'articles' }
}
*/

The rewrite formula is

routeHandler = requestPath.replace(routePath, routeHandler)

The route params will be converted to capture groups, so can be accessed by $1, $2, ....

Use ES2018 named capture groups:

const router = new Router([
  [/\/member\/(?<id>\d+)\/(?<page>[^/]+)$/, '/member/$<page>']
])

router.find('/member/234/profile')

/*
result:
{
  method: 'GET',
  path: '/member/234/profile',
  handler: '/member/profile',
  params: { id: '234', page: 'profile' }
}
*/
test

Function. Optional. Your custom test function to test against the request. If test function is defined, the route will be matched only if:

  1. The request path is matched with route's path
  2. The test function is passed (returns true)

Function signature:

function test(matchedRoute, testArg) {
  // should return true or false
}

matchedRoute: Object.

{
  method,
  path,
  handler,
  params
}

testArg: Arguments passed by router.find(method?, path, testArg?).

router.add(method?, path, handler, test?)

Adds a route to route table.

method is optional, it defaults to GET.

Every HTTP method has a shortcut alias:

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

router.find(method?, path, testArg?)

Finds the route which matches the method and path, and passes the test function if thers is one, or null if no route matches.

Params:
method: String. Optional. The request method. If omitted, defaults to GET.
path: String. The request method.
testArg: Any. Optional. Argument provides to route test function.

Returns:

{
  method,
  path,
  handler,
  params
}

License

MIT

Keywords

FAQs

Package last updated on 19 Dec 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc