@spa-tools/utilities
interpolateUrl()
The interpolateUrl<S>()
function interpolates state into a templated URL string.
The generic S
type is used to define the type of the provided state that is used
for interpolation and must extend Record<string, never>
.
Usage
import { interpolateUrl } from '@spa-tools/utilities';
const urlTemplate = '/users/:userId/products?version=:version&assetPath=:assetPath';
const state = {
assetPath: '/products/assets/',
sortBy: 'productName',
sortDir: 'asc',
userId: '123',
};
const interpolatedUrl1 = interpolateUrl(urlTemplate, state, {
addUnusedStateToQueryString: true,
});
console.log(interpolatedUrl1.url);
// --> '/users/123/products?assetPath=/products/assets/&sortBy=productName&sortDir=asc'
const interpolatedUrl2 = interpolateUrl(urlTemplate, state, {
discardOrphanedQueryStringPlaceholders: false,
});
console.log(interpolatedUrl2.url);
// --> '/users/123/products?version=:verson&assetPath=/products/assets/'
const interpolatedUrl3 = interpolateUrl(urlTemplate, state, {
preEncodeQueryStringValuesForKeys: ['assetPath'],
});
console.log(interpolatedUrl3.url);
// --> '/users/123/products?assetPath=%2Fproducts%2Fassets%2F'
Arguments
Name | Type | Required? | Default | Description |
---|---|---|---|---|
urlTemplate | string | yes | - | The URL template string to interpolate |
state | S | no | {} | The state used to interpolate |
options | InterpolateUrlOptions | no | See InterpolateUrlOptions | The options for interpolation |
Returns
Returns an InterpolatedUrlResult<S>
object.
InterpolateUrlOptions
The InterpolateUrlOptions
type is used to define the options for the interpolateUrl()
function.
Properties
Name | Type | Required? | Default | Description |
---|---|---|---|---|
addUnusedStateToQueryString | boolean | no | false | When true, any state that is not used to interpolate the URL will be added to the query string. |
discardOrphanedQueryStringPlaceholders | boolean | no | true | When true, any query string placeholders that are not used to interpolate the URL will be discarded. |
preEncodeQueryStringValuesForKeys | string[] | no | [] | An array of query string keys whose values should be pre-encoded (resulting in double-encoding). |
InterpolatedUrlResult
The InterpolatedUrlResult<S>
type is used to define the result of the interpolateUrl()
function.
Properties
Name | Type | Description |
---|---|---|
unmatchedParamState | Partial<S> | The unused state that was not interpolated into the URL path's params |
url | string | The interpolated URL |