Skip to main content
@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

NameTypeRequired?DefaultDescription
urlTemplatestringyes-The URL template string to interpolate
stateSno{}The state used to interpolate
optionsInterpolateUrlOptionsnoSee InterpolateUrlOptionsThe options for interpolation

Returns

Returns an InterpolatedUrlResult<S> object.

InterpolateUrlOptions

The InterpolateUrlOptions type is used to define the options for the interpolateUrl() function.

Properties

NameTypeRequired?DefaultDescription
addUnusedStateToQueryStringbooleannofalseWhen true, any state that is not used to interpolate the URL will be added to the query string.
discardOrphanedQueryStringPlaceholdersbooleannotrueWhen true, any query string placeholders that are not used to interpolate the URL will be discarded.
preEncodeQueryStringValuesForKeysstring[]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

NameTypeDescription
unmatchedParamStatePartial<S>The unused state that was not interpolated into the URL path's params
urlstringThe interpolated URL