Giter Club home page Giter Club logo

tiny-request-router's Introduction

tiny-request-router

Fast, generic and type safe router (match request method and path).

Features

  • Minimal and opinionless router, can be used in any script and environment.
  • Matches a request method (e.g. GET) and a path (e.g. /foobar) against a list of routes
  • Uses path-to-regexp, which is used by express and therefore familiar
  • Allows wildcards (e.g. /user/(.*)/age) and named parameters (e.g. /info/:username/:age)
  • Will not call your handlers automatically, as it only cares about matching
  • Battle hardened in production (Cloudflare Worker with 10M requests per day)
  • No magic, no assumptions, no fluff, type safe, tested

Route testing

Installation

yarn add tiny-request-router
# or
npm install --save tiny-request-router

Usage (JavaScript/TypeScript)

import { Router } from 'tiny-request-router'
// NodeJS: const { Router } = require('tiny-request-router')

const router = new Router()

router
  .get('/(v1|v2)/:name/:age', 'foo1')
  .get('/info/(.*)/export', 'foo2')
  .post('/upload/user', 'foo3')

const match1 = router.match('GET', '/v1/')
// => null

const match2 = router.match('GET', '/v1/bob/22')
// => { handler: 'foo1', params: { name: 'bob', age: '22' }, ... }

Make your handlers type safe (TypeScript)

import { Router, Method, Params } from 'tiny-request-router'

// Let the router know that handlers are async functions returning a Response
type Handler = (params: Params) => Promise<Response>

const router = new Router<Handler>()
router.all('*', async () => new Response('Hello'))

const match = router.match('GET' as Method, '/foobar')
if (match) {
  // Call the async function of that match
  const response = await match.handler()
  console.log(response) // => Response('Hello')
}

Example: Cloudflare Workers (JavaScript)

Use something like wrangler to bundle the router with your worker code.

import { Router } from 'tiny-request-router'

const router = new Router()
router.get('/worker', async () => new Response('Hi from worker!'))
router.get('/hello/:name', async params => new Response(`Hello ${params.name}!`))
router.post('/test', async () => new Response('Post received!'))

// Main entry point in workers
addEventListener('fetch', event => {
  const request = event.request
  const { pathname } = new URL(request.url)

  const match = router.match(request.method, pathname)
  if (match) {
    event.respondWith(match.handler(match.params))
  }
})

API

Table of Contents

Type: ("GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS")

Valid HTTP methods for matching.


Extends: TokensToRegexpOptions

Optional route options.

Example:

// When `true` the regexp will be case sensitive. (default: `false`)
sensitive?: boolean;

// When `true` the regexp allows an optional trailing delimiter to match. (default: `false`)
strict?: boolean;

// When `true` the regexp will match to the end of the string. (default: `true`)
end?: boolean;

// When `true` the regexp will match from the beginning of the string. (default: `true`)
start?: boolean;

// Sets the final character for non-ending optimistic matches. (default: `/`)
delimiter?: string;

// List of characters that can also be "end" characters.
endsWith?: string;

// Encode path tokens for use in the `RegExp`.
encode?: (value: string) => string;

Extends: Route<HandlerType>

The object returned when a route matches.

The handler can then be used to execute the relevant function.

Example:

{
  params: Params
  matches?: RegExpExecArray
  method: Method | MethodWildcard
  path: string
  regexp: RegExp
  options: RouteOptions
  keys: Keys
  handler: HandlerType
}

class: Router

Tiny request router. Allows overloading of handler type to be fully type safe.

Example:

import { Router, Method, Params } from 'tiny-request-router'

// Let the router know that handlers are async functions returning a Response
type Handler = (params: Params) => Promise<Response>

const router = new Router<Handler>()

List of all registered routes.


Add a route that matches any method.


Add a route that matches the GET method.


Add a route that matches the POST method.


Add a route that matches the PUT method.


Add a route that matches the PATCH method.


Add a route that matches the DELETE method.


Add a route that matches the HEAD method.


Add a route that matches the OPTIONS method.


Returns: (RouteMatch<HandlerType> | null)

Match the provided method and path against the list of registered routes.

Example:

router.get('/foobar', async () => new Response('Hello'))

const match = router.match('GET', '/foobar')
if (match) {
  // Call the async function of that match
  const response = await match.handler()
  console.log(response) // => Response('Hello')
}

More info

Please check out the tiny source code or tests for more info.

License

MIT

tiny-request-router's People

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

tiny-request-router's Issues

Query string support?

Hey @berstend - great little library, and definitely helps fill the gap in DX when writing lightweight APIs with Cloudflare Workers...

Quick question:

How would one access query params, or anything else on the original request (from inside the route handler)? I find first class support for route params, which is great, but that's it!

Example:

import { Router } from 'tiny-request-router'
import { asJSON, handleEvent } from './utils' // self-explanatory

const router = new Router()

router.get('/params/:id?', async (params, ...other) => asJSON({ ...params, ...other })
// for GET /params/foo?q=bar, you receive only { id: 'foo' } as a response...
// nothing else passed to the route handler to extract query params from

addEventListener('fetch', handleEvent(router))

I'd love to see something a bit more robust for future extensions/features, but with route params as THE first class citizen in the function handler, naming collisions are likely to occur. If instead of a handler payload like:

{ 
  param1: 'value',
  params2: 'value,
}

... you did something like:

{ 
  params: { 
    param1: 'value',
    param1: 'value',
  },
  query: {
    whatever: 'value',
  },
  ...anythingElseYouThinkOfLater
}

router.get('/example/:id', async ({ params, query }) => new Response(`Found id of ${params.id} and query of ${JSON.stringify(query)}`)

...you free yourself up to extend later without problems. Conversely, if you want to maintain backwards compatibility for now, you could simply use this more extensible pattern on a second param with affecting anyone already using this. That would allow for the easiest notation for those only concerned with route params, while still granting access to more powerful future features that others may be willing to dig for.

router.get('/example1/:id', async ({ id }) => new Response(`Found id of ${id}`))
router.get('/example2/:id', async ({ id }, { params, query }) => new Response(`Found id of ${id} and query of ${JSON.stringify(query)}`))

Query parameters?

Congrats on launching the new router, it is really neat and a bit more flexible than the last one.

It's great that we can use named parameters, I used it frequently with the previous router.

But what about query parameters? Like: mydomain.com/blog/post?id=333

Query parameters in path cause exception

I understand query parameters are not supported for routing but even using a path with them throws exception:

import { Router, Method } from 'tiny-request-router'

const router = new Router()
router.post('/v1/relays', handleAddRelay);
router.post('/?action=host', handleInitHost);

Causes:

Uncaught TypeError: Unexpected MODIFIER at 1, expected END\n  at line 21 in h\n  at line 21 in i\n  at line 21 in a\n  at line 21 in s\n  at line 21 in e._push\n  at line 21 in e.post\n  at line 1\n  at line 1 in n\n  at line 1\n  at line 1\n

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.