Router

Moduleejs.web
Definition class Router
InheritanceRouter inherit Object
Specifiedejscript-2.5
StabilityPrototype.
Example
var r = new Router

//  Match /some/path and run myCustomApp to generate a response. 
//  Target is data for myCustomApp.
r.add("/some/path", {response: myCustomApp, target: "/other/path"})

//  Match /User/register and run MvcApp with controller == User and 
//  action == "register"
r.add("\@/User/register")

//  Add route for files with a ".es" extension and use the ScriptApp 
//  to generate the response
r.add(/\.es$/i, {response: ScriptApp})

//  Add route for directories and use the DirApp to generate the response
r.add(Router.isDir, {name: "dir", response: DirApp})

//  Add routes for RESTful routes for URIs starting with "/User" and 
//  respond using MvcApp
r.addResources("User")

//  Manually create restful routes using the given URI template patterns
r.add("/{controller}",           {action: "create", method: "POST"})
r.add("/{controller}/init",      {action: "init"})
r.add("/{controller}",           {action: "index"})
r.add("/{controller}/{id}/edit", {action: "edit"})
r.add("/{controller}/{id}",      {action: "show"})
r.add("/{controller}/{id}",      {action: "update", method: "PUT"})
r.add("/{controller}/{id}",      {action: "destroy", method: "DELETE"})
r.add("/{controller}(/do/{action})")

//  Add route for upper or lower case "D" or "d". Run the default app: MvcApp, 
//  Dash contoller, refresh action.
r.add("/[Dd]ash/refresh", "\@Dash/refresh")

//  Add route for an "admin" application. This sets the scriptName to "admin" 
//  and expects an application to be located at the directory "myApp"
r.add("/admin/", {location: { scriptName: "/control", dir: "my"})

//  Rewrite a request for "old.html" to new.html
r.add("/web/old.html", 
    {rewrite: function(request) { request.pathInfo = "/web/new.html"}})  

//  Handle a request with a literal response
r.add("/oldStuff/", {response: {body: "Not found"} })

//  Handle a request with an inline function
r.add("/oldStuff/", {response: function(request) { return {body: "Not found"} }})

//  A custom matching function to match SSL requests
r.add(function (request) {
    if (request.scheme == "https") {
        request.params["security"] = "high"
        return true
    }, {
        name: "secure", action: "private" 
    }
})

//  A matching function that rewrites a request and then continues matching other routes
r.add(function (request) {
    if (request.uri.startsWith("/old")) {
        request.uri = request.uri.toString().trimStart("/old")
        return false
    }
})

//  Route based on header values
r.add(function (request) {
    if (request.header("user-agent").contains("Chrome")) {
        return true
    }
})

//  Set request parameters with values from request
r.add("/custom", {action: "display", params: { from: "{uri}", transport: "{scheme}" })

//  Nest matching routes
let outer = r.add("/blog", {target: "/post/index"})
r.add("/comment", {target: "/comment/{action}/{id}", outer: outer})

//  Match with regular expression. The sub-match is available via $N parameters
r.add(/^\/Dash-((Mini)|(Full))$/, 
    {controller: "post", action: "list", params: {kind: "$1"}}
)

//  Conditional matching. Surround optional tokens in "()"
r.add("/Dash(/{product}(/{branch}(/{configuration})))", {   
    name: "dash", 
    method: "POST", 
    controller: "Dash", 
    action: "index",
})

//  Replace the home page route
r.addHome("/Status")

//  Display the route table to the console
r.show()

@stability prototype

The Router class manages incoming HTTP requests to the appropriate location application for servicing.

The Route class supports configurable user-defined routes. Each application should create a Router instance and then attach matching routes.

The Router works by defining routes in a route table. For rapid routing, routes are grouped into sets of routes with the same leading URI path segment. For example: the route template "/User/login" would be put into the "User" route set. If a route template is a function or regular expression, the route is added to the "Global" route set.

The Request.pathInfo and other Request properties are examined when selecting a matching route. The request's leading URI pathInfo segment is used to select a route set and then the request is matched against each route in that set. Routes are matched in the order in which they are defined.


Properties

QualifiersPropertyTypeDescription
static const RestfulStringSymbolic constant for Router() to add top-level routes for directory, *..es, *..ejs, generic routes for RESTful resources and a catchall route for static pages.
static const TopStringSymbolic constant for Router() to add top-level routes for directory, *..es, *..ejs and a catchall route for static pages. Use of this constant will not add routes for MVC content or RESTful resources.
static const WebSiteStringnull
defaultAppFunctionDefault application to use when unspecified by a route.
routesObjectRoutes indexed by first component of the URI path/template.

Router Class Methods

QualifiersMethod
static isDir(request)
 Function to test if the Request.filename is a directory.

Router Instance Methods

QualifiersMethod
Router(routeSet: String = Restful, options: Object = expression)
 Create a Router instance and initialize routes.
add(template: Object, options: Object = null): Route
 Add a route.
addCatchall(): Void
 Add a catch-all route for static content.
addDefault(response: Object): Void
 Add a default MVC controller/action route.
addHandlers(): Void
 Add routes to handle static content, directories, "es" scripts and stand-alone ejs templated pages.
addHome(target: Object): Void
 Add a home page route.
addResource(name: Object): Void
 Add restful routes for a singleton resource.
addResources(name: Object): Void
 Add restful routes for a resource collection.
addRestful(): Void
 Add default restful routes for resources.
lookup(options: Object): Route
 Lookup a route by name.
remove(name: String): Void
 Remove a route.
reset(request): Void
 Reset the request routing table by removing all routes.
route(request): Route
 Route a request.
show(extra: String = null): Void
 Show the route table.

Method Detail

ejs.web Router(routeSet: String = Restful, options: Object = expression)
Description
Create a Router instance and initialize routes.
Parameters
routeSet: String Optional name of the route set to add. Supports sets include: Router.Top and Router.Restful. The Top routes provide top level routes for pages with extensions ".ejs", and ".es" as well as for static content (see addHandlers addCatchall). The Restful routes provide default Controller/Action routes according to a RESTful paradigm (see addRestful). The routeSet can also be set to null to add not routes. This is useful for creating a bare Router instance. Defaults to Top. [default: Restful]
options: Object Options to apply to all routes. [default: expression]
Options
workersBoolean If true, requests should be execute in a worker thread if possible. The worker thread will be pooled when the request completes and will be available for subsequent requests.
Throws
Error: for an unknown route set.

add(template: Object, options: Object = null): Route
Description
Add a route.
Parameters
template: Object String or Regular Expression defining the form of a matching URI (Request.pathInfo). If options are not provided and the template arg is a string starting with " @", the template is interpreted both as a URI and as providing the options. See options below for more details.
options: Object Route options representing the URI and options to use when servicing the request. If it is a string, it may begin with a " @" and be of the form " @[controller/]action". In this case, if there is a "/" delimiter, the first portion is a controller and the second is the controller action to invoke. The controller or action may be absent. For example: " @Controller/", " @action", " @controller/action". If the string does not begin with an " @", it is interpreted as a literal URI. For example: "/web/index.html". If the options is an object hash, it may contain the options below:. [default: null]
Options
actionAction method to service the request if using controllers. This may also be of the form "controller/action" to set both the action and controller in one property.
constraintsObject Object hash of properties whose values are constrained. The property names are the field names to be constrained and their values are regular expressions for which the actual URI values must match for the route to match.
controllerController to service the request.
nameName to give to the route. If absent, the name is created from the controller and action names. The route naming rules are: 1. Use options.name if provided, else 2. Use any action name, else 3. Use "index" The action name is sleuthed from the template if no options are given.
outerParent route. The parent's template and parameters are appended to this route.
paramsOverride parameter to provide to the request in the Request.params.
nameName for the route.
methodString|RegExp HTTP methods to support.
limitsLimits object for the requests on this route. See HttpServer.limits.
locationApplication location to serve the request. Location contains two properties: scriptName which is the string URI prefix for the application and dir which is a Path to the physical file system directory containing the applciation.
paramsOverride request parameters.
parentOuter parent route.
redirectRedirect requests on this route to this URI.
response(Function|Object) This can be either a function to serve the request or it can be a response hash with status, headers and body properties. The function should have this signature: function (request: Request): Object.
rewriteRewrite function. This can rewrite request properties.
setRoute set name in which to add this route. Defaults to the first component of the template if the template is a string, otherwise "".
targetTarget for the route. This can be a Uri path or a controller/action pair: " @[controller/]action".
Example
Route("/{controller}(/{action}(/{id}))/", { method: "POST" })
Route("/User/login", {name: "login" })
Route("\@/User/login")
@option name Name for the route

addCatchall(): Void
Description
Add a catch-all route for static content.

addDefault(response: Object): Void
Description
Add a default MVC controller/action route. This consists of a "/{controller}/{action}" route. All HTTP method verbs are supported.

addHandlers(): Void
Description
Add routes to handle static content, directories, "es" scripts and stand-alone ejs templated pages.

addHome(target: Object): Void
Description
Add a home page route. This will add or update the "home" page route.
Parameters
target: Object Target to invoke when the home page is accessed.

addResource(name: Object): Void
Description
Add restful routes for a singleton resource. Supports member CRUD actions: edit, show, update, and custom actions. The restful routes defined are:
Method  URL                   Action
GET     /controller/edit      edit        Display a resource form suitable for editing
GET     /controller           show        Display a resource (not editable)
PUT     /controller           update      Update a resource (idempotent)
ANY     /controllers/action   *            Other custom actions
The default route is used when constructing URIs via Request.link.
Parameters
name: Object Name of the resource to route. Can also be an array of names.

addResources(name: Object): Void
Description
Add restful routes for a resource collection. Supports CRUD actions: edit, index, show, create, update, destroy. The restful routes defined are:
Method  URL                     Action
GET     /controller             index       Display an overview of the resource
GET     /controller/init        init        Initialize and display a blank form for a new resource
POST    /controller             create      Accept a form creating a new resource

GET /controller/1/edit edit Display a resource form suitable for editing GET /controller/1 show Display a resource (not editable) PUT /controller/1 update Update a resource (idempotent) DELETE /controller/1 destroy Destroy a resource (idempotent)

ANY /controller/action default Other custom actions
The default route is used when constructing URIs via Request.link.
Parameters
name: Object Name of the resource to route. Can also be an array of names.

addRestful(): Void
Description
Add default restful routes for resources. This adds default routes for generic resources. Supports CRUD actions: edit, index, show, create, update, destroy. The restful routes defined are:
Method  URL                     Action
GET     /controller             index       Display an overview of the resource
GET     /controller/init        init        Initialize and display a blank form for a new resource
POST    /controller             create      Accept a form creating a new resource

GET /controller/1/edit edit Display a resource form suitable for editing GET /controller/1 show Display a resource (not editable) PUT /controller/1 update Update a resource (idempotent) DELETE /controller/1 destroy Destroy a resource (idempotent)

ANY /controller/action default Other custom actions
The default route is used when constructing URIs via Request.link.

static isDir(request)
Description
Function to test if the Request.filename is a directory.
Parameters
request Request object to consider.
Returns
True if request.filename is a directory.

lookup(options: Object): Route
Description
Lookup a route by name. The route name is determined by the options provided when the route was created. Action names will be sleuthed from the template if no options provided. Outer routes are pre-pended if defined.
Parameters
options: Object Route description. This can be either string or object hash. If it is a string, it should be of the form "controller/action". If the options is an object hash, it should have properties controller and action. The controller is used as the index for the route set. The action property is the index for the route name.
Returns
Route object or null if the route is not found.

remove(name: String): Void
Description
Remove a route.
Parameters
name: String Name of the route to remove. Name should be of the form "controller/action" where controller is the index for the route set and action is the index for the route name.

reset(request): Void
Description
Reset the request routing table by removing all routes.

route(request): Route
Description
Route a request. The request is matched against the configured route table. The call returns the web application to execute.
Parameters
request The current request object.
Returns
The web application function of the signature: function app(request: Request): Object.

show(extra: String = null): Void
Description
Show the route table.
Parameters
extra: String Set to "full" to display extra route information. [default: null]