Learn R Programming

routing (version 1.1.1)

Router: Router

Description

A port of the pillarjs/router package for R. Maintains an ordered stack of layers; each layer pairs a path pattern with a middleware function, a nested Router, or a Route object. Middleware and nested routers are added via $use(); routes are added via $route() or the HTTP-verb shortcuts. When a request arrives, the stack is walked in order and each matching layer is invoked until the request is handled or the stack is exhausted.

Important details

  • forward() instead of next() -- next is a reserved word in R. forward("route") and forward("router") work identically to their Express counterparts.

  • forward is implicit -- handlers do not need to declare forward as an argument to call it; it is automatically injected into the handler's formals if absent. function(req, res) { forward() } works just as well as function(req, res, forward) { forward() }.

  • forward is auto-called -- if a handler returns without calling forward() or sending a response, forward() is called automatically.

  • Error handlers take three arguments -- write error handlers as (err, req, res); forward is injected automatically as the fourth argument.

HTTP verb shortcuts

$get(), $post(), $put(), $delete(), etc. (one per HTTP verb) and $all() are convenience wrappers with signature (path, ...) equivalent to router$route(path)$<verb>(...). They return self invisibly for chaining.

Arguments

Methods


Router$new()

Creates a new Router.

Usage

Router$new(caseSensitive = FALSE, mergeParams = FALSE, strict = FALSE)

Arguments

caseSensitive

(logical(1))
When TRUE, path matching is case-sensitive (/Foo does not match /foo). Default FALSE.

mergeParams

(logical(1))
When TRUE, req$params from a parent router are merged with those of this router instead of being replaced. Default FALSE.

strict

(logical(1))
When TRUE, trailing slashes are significant (/foo/ does not match /foo). Default FALSE.

Returns

A new Router object.


Router$handle()

Dispatches a request through the router's layer stack. Normally called by a server or a parent router rather than directly.

Usage

Router$handle(req, res = NULL, callback = NULL)

Arguments

req

(environment)
Rook request environment.

res

(Response)
Response object.

callback

(function)
Called when no layer matched or an unhandled error occurred.


Router$use()

Mounts one or more middleware handlers, optionally scoped to a path prefix. A Router may be passed and will be wrapped automatically. Functions whose first parameter is named err are treated as error handlers.

Usage

Router$use(...)

Arguments

...

(function | list)
An optional leading character(1) path prefix, followed by one or more handler functions, nested lists of functions, or another Router.

Returns

self invisibly.


Router$route()

Creates a new Route for path and appends it to the stack.

Usage

Router$route(path)

Arguments

path

(character(1))
Path pattern.

Returns

The new Route invisibly.


Router$param()

Registers a callback triggered whenever a named route parameter is present in a matched route. The callback runs before the route handler.

The callback signature is function(req, res, value, name):

  • value -- the captured value of the parameter.

  • name -- the parameter name (character).

Usage

Router$param(name, fn)

Arguments

name

(character(1))
Name of the route parameter to watch.

fn

(function)
Callback with signature function(req, res, value, name).

Returns

self invisibly.

Examples

router <- Router$new()

router$param("id", function(req, res, value, name) { user <- findUser(value) req$user <- list(id = value, name = user$name) forward() })

router$get("/user/:id", function(req, res) { res$send(paste("user:", req$user$name)) })


Router$static()

Registers a directory of static files to be served at a given URL prefix. Static files are served directly by httpuv's background I/O thread without invoking R.

Usage

Router$static(root, url, ...)

Arguments

root

(character(1))
Local filesystem path to the directory containing the files to serve.

url

(character(1))
URL prefix at which the files will be available (e.g. "/static").

...

Additional arguments passed to httpuv::staticPath().

Returns

self invisibly.


Router$getStack()

Returns the internal layer stack.

Usage

Router$getStack()

Returns

list of Layer objects.


Router$clone()

The objects of this class are cloneable with this method.

Usage

Router$clone(deep = FALSE)

Arguments

deep

Whether to make a deep clone.

Examples

Run this code
router <- Router$new()

router$get(
  "/get",
  function(req, res) {
    res$send("Hello there!")
  }
)$post(
  "/post",
  function(req, res) {
    res$send("Goodbye!")
  }
)

router$get(
  "/hello",
  function(req, res) {
    forward()
  },
  function(req, res) {
    res$send("Hello!")
  }
)

router$post("/bye", function(req, res) {
  res$send("Bye!")
})

router$route("/hi")$get(function(req, res) {
  res$send("handling a GET request!")
})$post(function(req, res) {
  res$send("handling a POST request!")
})

router$get(
  c("/path", "/another-path"),
  function(req, res) {
    res$send("Hola!")
  }
)

## ------------------------------------------------
## Method `Router$param()`
## ------------------------------------------------

router <- Router$new()

router$param("id", function(req, res, value, name) {
  user <- findUser(value)
  req$user <- list(id = value, name = user$name)
  forward()
})

router$get("/user/:id", function(req, res) {
  res$send(paste("user:", req$user$name))
})

Run the code above in your browser using DataLab