Routing
Kikwit supports both explicit and implicit routing.
Explicit routing
Explicit routing is when a controller or action is tagged with a @route
decorator.
import { controller, get, route } from 'kikwit';
@route('/prods')
@controller
export class Products {
@route('/catalog')
@get
list(context) {
...
}
}
In the example above, the list
action will be accessible at /prods/catalog
.
Implicit routing
Implicit routing is when a controller or action is not tagged with a @route
decorator.
import { controller, get } from 'kikwit';
@controller
export class Products {
@get
list(context) {
...
}
}
In the example above, the list
action will be accessible at /products/list
.
Route parameters
Routes can define dynamic parts in the following format :KEY
where KEY is the key used to access the corresponding value from the request context.
import { controller } from 'kikwit';
@controller
export class Products {
@route('/show/:id')
@get
details(context) {
context.send(context.params.id);
}
}
With the route above, a GET /products/show/34
request will result in a context params's id of 34.
Route parameters can use regular expressions as constraints in the following format :KEY<REGEX>
where REGEX is the regular expression constraint.
Using the example above, if the request was GET /products/show/laptop
then the context.params.id
would be laptop. But if the action route was
@route('/show/:id<\\d+>')
instead then GET /products/show/laptop
request would not be dispatched to the details
action.
Route parameters can also be specified on the controller level route decorator.
Route names
Action routes can specify a route name which helps generate URLs targeting the route.
import { controller } from 'kikwit';
@controller
export class Products {
@route('/show/:id', 'productDetails')
@get
details(context) {
context.send(context.params.id);
}
}
The context's routeURL(name [, params] [, query] [, validate = true])
method can be called to generate the URL.
i.e. a link to the details action's route can be generated using the following
context.routeURL('productDetails', { id: 34 })
The above would generate the string /products/show/34.
Query strings can be added to the generated URL with the help of the third argument of the context's routeURL(...)
method.
context.routeURL('productDetails', { id: 34 }, { offset: 10, pageSize: 20})
The above would generate the string /products/show/34?offset=10&pageSize=20.
The validate argument validates params values against route constraints (if any). Passing false
skips any validation.