url-sweatshirt
Wrap your URLs in a warm layer of helper functions.
Projects like JsRoutes are great when your JavaScript is tightly integrated
with a Rails backend. However, if you want to reduce coupling between your
frontend and backend code, you're going to need to manage your routes manually.
url-sweatshirt
eases that transition by generating Rails-like URL helpers for
you.
var generate = generate;var userPostUrl = ;// all return '/users/1/posts/2');;;// returns '/users/1/posts/2?q=javascript';// returns '/users/1/posts/2?q=javascript&foo=bar';
Defaults
When you define a URL, you can pass in defaults for both path parameters and query parameters.
var categoryUrl = ;// returns '/categories/all?locale=en';
Callers can then override the defaults. They can also remove a default query
parameter by passing null
.
// returns '/categories/books';
Special parameters
_anchor
, _host
, and _protocol
are special:
var fancyUrl =;// returns 'https://www.example.com/#post-5';
If you provide _host
but not _protocol
, you'll get a protocol-relative URL
(i.e., one starting with //
).
Shared defaults
If you need to define a bunch of helpers with shared default parameters, you
can use the withDefaults
function. It takes a callback and passes in a
version of generate
with the given defaults baked in.
var withDefaults = withDefaults;var urls = {};;// returns '//api.example.com/users/1'urls;
Using a fancier query encoder
By default, the query string is built using a simple function that calls
toString()
on param values and then URI-encodes the param keys and values.
For some use cases, it's helpful to use alternate strategies for this -- for
example, you might want to use jQuery's $.param
to convert objects and arrays
into Rails-style bracket notation. You can accomplish this by calling the
function exported from the url-sweatshirt
module and passing in a function
with the appropriate signature (takes a single object param and returns a
string).
var simpleGenerate = generate;var simpleHomeUrl = ;var complexGenerate = $paramgenerate;var complexHomeUrl = ;// returns '/?a=1&b=[object%20Object]';// returns '/?a=1&b[c]=2&b[d]=3`;
Features that aren't supported yet
- Optional and splat params.
- Lots of other features that we didn't need yet. Pull requests welcome!