Skip to content

A url-template validator, expander and inspector as defined by RFC 6570

License

SorinGFS/url-templates

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

title description
URL Templates
A URL Template validator, expander and inspector

Overview

A URL Template validator, expander and inspector — fully RFC 6570 compliant. Passes all the 252 tests from the uritemplate-test suite. Minimal, zero dependency, sync API; exposes AST for linters/interfaces and both validated and non-validated expansion paths.

Install

npm i url-templates

Usage

This library provides the following url-template functions:

Validation

const { isUrlTemplate } = require('url-templates');
try {
    console.log('valid:', isUrlTemplate('/users/{id}')); // true
} catch (error) {
    console.error('invalid:', error.message);
}

Note: It returns true or throws an error.

Inspection

const { inspect } = require('url-templates');
try {
    console.dir(inspect('/search{?q*,lang:2}'), { depth: null }); 
    // [ '/search', { '?': [ { key: 'q', explode: true }, { key: 'lang', limit: 2 } ] } ]
} catch (error) {
    console.error('invalid:', error.message);
}

Note: Same as with isUrlTemplate, but if valid returns the parsed AST instead of true.

Expansion with validation

const { parseTemplate } = require('url-templates');
try {
    console.log(parseTemplate('/items/{id}').expand({ id: 42 })); // '/items/42'
} catch (error) {
    console.error('parse/validation error:', error.message);
}

Note: If valid returns the expand(vars) function which returns the expanded url-template. Otherwise, it throws an error. The expand function also throws error if limit is defined on objects (isUrlTemplate function cannot know that without runtime vars).

Expansion without validation

const { compile } = require('url-templates');
console.log(compile('/broken{').expand({})); // returns '/broken{'; invalid parts left for postprocessing
console.log(compile('/good{id}').expand({id:42})); // returns '/good42'; 

Note: Returns a usable expander without validation (for cases where validation is done elsewhere, or for the cases where some sort of postprocessing will follow).

About

A url-template validator, expander and inspector as defined by RFC 6570

Resources

License

Stars

Watchers

Forks

Packages

No packages published