route: Routing

Description Usage Arguments Details Value See Also Examples

Description

Within prairie, a route is thought of as a mapping between any number of methods, specified by method, and a URI, path. A route is never assigned more than a single path. However, because path is treated as a regular expression a single route may be created to match different client requests. Further details below.

Usage

1
2
3
route(method, path, handler)

is.route(x)

Arguments

method

A character vector specifying an HTTP method(s), such as "get", "post", or "put", case-insensitive.

path

A character string specifying which URI the route will handle.

handler

A function whose return value is an object of class response, see the Details section below.

Details

Arguments:

method

method is a character vector which specifies at least one HTTP method. Alternatively, the keywords "all" or "ALL" may be used to specifiy the route to accept any HTTP method. Custom methods may be used, but are not advised.

method is converted to upper case, so "GET" and "get" are equivalent.

path

path is a character string and is treated as a regular expression. When specifying a path it is unnecessary to include a beginning /. To create a route for the root resource, '/', one may specify '^$' as path.

handler

handler is a function with a single argument req. When an application receives a request, this HTTP request is parsed into a request object and is made available to handler as req. This allows routes to handle specific HTTP header fields included in the request as well as arguments passed as part of the URI.

Matching:

An incoming request is matched to a route by pattern matching each route's path to the request's URI. Matches are tested for using grepl. The order routes are added to an application is important as matches are checked for sequentially and only the handler of the first matching route is run.

Value

A route object.

See Also

request, response

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Typically, routes are created and added to an
# application inside app(), but standalone route
# objects may be created and added later.

# matches only GET requests
route(
  'GET',
  '^transformers/[a-z_]+$',
  function(req) {
    res <- response()

    if (uri(req) == '/transformers/beast_wars') {
      body(res) <- 'Right on!'
    } else {
      body(res) <- 'I can dig that.'
    }

    res
  }
)

# matches both GET and POST requests
route(
  c('GET', 'POST'),
  '^blog/comments$',
  function(req) {
    res <- response()

    if (method(req) == 'get') {
      body(res) <- 'Get your own comments!'
    } else {
      body(res) <- 'Thanks for commenting'
    }

    res
  }
)

nteetor/prairie documentation built on May 24, 2019, 9:56 a.m.