This plugin gives you an API for generating URLs dynamically in hapi using route ids and optional parameters, so you don't need to hardcode them into your views. This helps a bunch if you change the path structure of your routes, or move them into prefixed plugins in the future.
Features
- Let's you change paths without breaking existing links + redirects
- 100% test coverage
- Works with params (including wildcard, optional and multi-params)
- Configurable with options
Install
To download and add to dependencies run npm install --save hapi-to
Register with a server like any other hapi plugin with server.register()
:
var Hapi = ; var server= ;server; server;
After registering, hapi-to will decorate the hapi request object with a new method: request.to()
.
API
request.to(id, params, options)
Returns a URL to a route
id
- required route id. Set when creating a route with theconfig.id
property.params
- request parameters where:query
- an optional object of query string key-values. Will be stringified using the Qs module.params
- an optional object of path parameters. Number given must match route path. Each parameter value can be a string or an array of strings (for multi params)
options
- additional options which affect how the URL is generated where:rel
- Whether to generate a relative URL. Can betrue
orfalse
(default).secure
- a boolean or "match". Iftrue
the URL will be https, iffalse
will be http. If"match
" (the default) will match the x-forwarded-proto header or the current request's connection protocol (in that order).host
- string that sets the host in the URL. Default is to match the current request.
Example
var Hapi = ; var server = ;server; server; server;
If you run the above example and navigate to http://localhost:8080/ you will be redirected to http://localhost:8080/a/stitch/in/nine/saves/time?page=1
If you navigate to http://localhost:8080/multi you will be redirected to http://localhost:8080/never/gonna/give/you/up
Contributing
Issues and PRs are welcome. If you have any questions or suggestions please open an issue.