typed-uri-template
v1.0.0
Published
A typed URI template serializer.
Downloads
9
Readme
typed-uri-template
A typed URI template serializer.
Usage
import {
URITemplate,
asString,
asStrings,
asNumber,
asString,
asBoolean,
} from 'typed-uri-template';
const template = new URITemplate(
'/~{username}/{+path}/{filename}{?size}{&compressed}',
{
username: asString,
path: asStrings,
filename: asString,
size: asNumber,
compressed: asBoolean,
},
);
template.serialize({
username: 'nfroidure',
path: 'medias/music',
filename: 'HighwayToHell.mp3',
size: 10,
compressed: true,
});
// '/nfroidure/medias/music/HighwayToHell.mp3?size=10&compressed=true'
Matchers
In order to check types, you can define matchers like this:
import { URITemplate } from 'typed-uri-template';
import { YError } from 'yerror';
import type { ParameterMatcher } from 'typed-uri-template';
type Language = (typeof SUPPORTED_LANGUAGES)[number];
const SUPPORTED_LANGUAGES = ['fr', 'en'] as const;
export const asLanguage: ParameterMatcher<Language> = {
parse: (s) => {
const index = SUPPORTED_LANGUAGES.indexOf(s);
if (index === -1) {
throw new YError('E_BAD_LANGUAGE', s);
}
return SUPPORTED_LANGUAGES[index];
},
serialize: (s) => s,
isValid: (s) => typeof s === 'string' && SUPPORTED_LANGUAGES.includes(s),
type: 'value',
};
const template = new URITemplate('/blog/{language}/home', {
language: asLanguage,
});
template.serialize({
asLanguage: 'fr',
});
// '/blog/{language}/home'
A predefined set of matchers is available here.