url-tidy
v0.6.1
Published
[](https://badge.fury.io/js/url-tidy) [](https://opensource.org/licenses/Apache-2.0) 
// => fetch('https://example.com/api/users/1000/profile')URL Template Rules
You can put placeholders in the following locations:
- protocol
- hostname
- port (
number) - path
- query value
- query set (
objectorURLSearchParams) - fragment
url`${protocol}://${hostname}:${port}/${path}?queryKey=${queryValue}&${querySet}#${fragment}`Placeholder can be written only between each delimiter (://, :, /, ?, =, &, #) and interpolated strings are escaped properly.
Path Hierarchies
Placeholders for path can accept array or / separated string, and it supports URLs with variable path hierarchies.
const areaList = ["japan", "tokyo", "shinjuku"];
url`https://example.com/menu/${areaList}`
// => 'https://example.com/menu/japan/tokyo/shinjuku'
const areaStr = "japan/tokyo/shinjuku";
url`https://example.com/menu/${areaStr}`
// => 'https://example.com/menu/japan/tokyo/shinjuku'null
If the placeholder value is null, the placeholder and related text (like query key) are removed from the resulting URL.
const port = null;
const value1 = null;
const value2 = "value2";
const fragment = null;
url`https://example.com:${port}/api/users?key1=${value1}&key2=${value2}#${fragment}`
// => 'https://example.com/api/users?key2=value2'This behavior is useful when you want to implement paging query than URLSearchParams.
const word = "spicy food";
const page = 10;
const perPage = null; // use default
const limit = null; // use default
url`https://example.com/api/search?word=${word}&page=${page}&perPage=${perPage}&limit=${limit}`
// => 'https://example.com/api/search?word=spicy+food&page=10'Query Set
It accepts an object or URLSearchParams object as a query set and merges it with other queries. It is useful when you can pass the result of form validation library.
const searchParams = {
word: "spicy food",
safeSearch: false,
spicyLevel: Infinity,
}
url`https://example.com/api/search?${searchParams}`
// => 'https://example.com/api/search?word=spicy+food&safeSearch=false'Advanced Usage
Custom factory function can overwrite the some parts of the URL. It is good for specifies the API host that is from environment variables or credentials that should not be hard-coded in the source code:
protocolhostname: It can containsprotocoland/orport.portusernameandpassword: It is only available location to define in this library.
import { customFormatter } from 'url-tidy';
const url = customFormatter({
hostname: process.env.API_SERVER_HOST, // 'https://localhost:8080'
username: 'user',
password: 'pAssw0rd',
})
const id = 1000;
url`https://api-server/api/users/${id}/profile`
// => 'https://user:pAssw0rd@localhost:8080/api/users/1000/profile'
// "https://api-server" is a dummy string that is replaced with customFormatter()'s hostname option.
// You can avoid hard-coding the actual hostname in your project code.License
Apache-2.0
Reference
- Go Version: github.com/shibukawa/urlf
