1.0.0 • Published 5 years ago
@zakkudo/url v1.0.0
@zakkudo/url
Make working with urls enjoyable.
Why use this?
- Params are accepted as a separate object
- You can update the params on the fly before the string is serialized
- Supports interpolation of fragments of the url with the params
- Supports dynamic json stringification of complex options like
@zakkudo/query-string
Install
# Install using npm
npm install @zakkudo/url
# Install using yarn
yarn add @zakkudo/url
Examples
Generate URL with interpolation
import Url from '@zakkudo/url';
const url = new Url('http://backend/v1/users/:id/detail', {
page: 3,
id: '1234'
});
String(url); // 'http://backend/v1/users/1234/detail?page=3'
url.toString(); // 'http://backend/v1/users/1234/detail?page=3'
//Update the params after the fact
url.param.id = '5678';
String(url); // 'http://backend/v1/users/5678/detail?page=3'
//Update the url base after the fact
url.base = 'http://frontend/v1/users/:id/detail';
String(url); // 'http://frontend/v1/users/5678/detail?page=3'
Generate object using raw url
import Url from '@zakkudo/url';
const url = new Url('http://backend/v1/users?limit=20');
JSON.stringify(url); // {"base": "http://backend/v1/users", "params": {"limit": 20}}
Error handling
import Url from '@zakkudo/url';
import UrlError from @zakkudo/url/UrlError;
const url = new Url('http://backend/v1/users/:userId', {});
try {
String(url)
} catch (e) {
if (e instanceof UrlError) {
console.error(e.message); // `No replacement exists for userId in the params`
}
throw e;
}
API
@zakkudo/url~Url ⏏
Kind: Exported class
new Url(url, params, options)
Throws:
- UrlError On issues during serialization or construction of the url
- QueryStringError On issues during serialization or construction of the query string
Param | Type | Default | Description |
---|---|---|---|
url | String | The url pattern | |
params | Object | Params to interpolate or append to the url as a query string when serialized. | |
options | Object | Modifiers for how the query string object is contructed | |
options.unsafe | Boolean | false | Disable url escaping of key/value pairs. Useful for servers that use unsafe characters as delimiters |
@zakkudo/url/UrlError~UrlError ⇐ Error ⏏
Error class used by Url for raising errors generated for invalid errors.
Kind: Exported class
Extends: Error
new UrlError(message, url)
Param | Type | Description |
---|---|---|
message | String | A message describing the reason for the error. |
url | String | The related url fragment when the error was generated |
urlError.url
The related url fragment when the error was generated
Kind: instance property of UrlError
@zakkudo/url/QueryStringError~QueryStringError ⏏
Aliased error from package @zakkudo/query-string/QueryStringError
Kind: Exported class