13
头图

urlcat is a small JavaScript library that makes building URLs very convenient and prevents common mistakes.

characteristic:

  • Friendly API
  • no dependency
  • 0.8KB size after compression
  • Provide TypeScript types

Why use?

When calling an HTTP API, it is often necessary to add dynamic parameters to the URL:

const API_URL = 'https://api.example.com/';

function getUserPosts(id, blogId, limit, offset) {
  const requestUrl = `${API_URL}/users/${id}/blogs/${blogId}/posts?limit=${limit}&offset=${offset}`;
  // send HTTP request
}

As you can see, this minimal example is already hard to read. This is also incorrect:

  • I forgot that the API_URL constant had a slash at the end, so this resulted in a URL with repeated slashes ( https://api.example.com//users )
  • Embedded values need to be escaped with encodeURIComponent

I can use the built in URL class to prevent repeated slashes and URLSearchParams to escape the query string. But I still need to escape all path parameters manually.

const API_URL = 'https://api.example.com/';

function getUserPosts(id, blogId, limit, offset) {
  const escapedId = encodeURIComponent(id);
  const escapedBlogId = encodeURIComponent(blogId);
  const path = `/users/${escapedId}/blogs/${escapedBlogId}`;
  const url = new URL(path, API_URL);
  url.search = new URLSearchParams({ limit, offset });
  const requestUrl = url.href;
  // send HTTP request
}

Such a simple task, yet hard to read and tedious to write! This is where this small library can help you:

const API_URL = 'https://api.example.com/';

function getUserPosts(id, limit, offset) {
  const requestUrl = urlcat(API_URL, '/users/:id/posts', { id, limit, offset });
  // send HTTP request
}

This library will handle it like this:

  • escape all parameters
  • Connect all the parts (there is always exactly one / and ? between them)

how to use?

Currently, the package is distributed via npm. (Zip download and CDN coming soon).

npm install --save urlcat

Use in Node.js

Officially supports Node 10 and above. Since the code internally uses the URL and URLSearchParams classes, which are not available below v10, we cannot support these versions.

To build the full URL (most common use case):

const urlcat = require('urlcat').default;

To use any of the utility functions:

const { query, subst, join } = require('urlcat');

To use all exported functions:

const { default: urlcat, query, subst, join } = require('urlcat');

Use in Typescript

Officially supports TypeScript 2.1 and above.

To build the full URL (most common use case):

import urlcat from 'urlcat';

To use any of the utility functions:

import { query, subst, join } from 'urlcat';

To use all exported functions:

import urlcat, { query, subst, join } from 'urlcat';

Use in Deno

import urlcat from 'https://deno.land/x/urlcat/src/index.ts';

console.log(urlcat('https://api.foo.com', ':name', { id: 25, name: 'knpwrs' }));

API

ParamMap: object with string keys

For example, { firstParam: 1, 'second-param': 2 } is a valid ParamMap.

urlcat: build the full URL

function urlcat(baseUrl: string, pathTemplate: string, params: ParamMap): string
function urlcat(baseUrl: string, pathTemplate: string): string
function urlcat(baseTemplate: string, params: ParamMap): string

E.g:

  • urlcat('https://api.example.com', '/users/:id/posts', { id: 123, limit: 10, offset: 120 })
    → 'https://api.example.com/users/123/posts?limit=10&offset=120'
  • urlcat('http://example.com/', '/posts/:title', { title: 'Letters & "Special" Characters' })
    → 'http://example.com/posts/Letters%20%26%20%22Special%22%20Characters'
  • urlcat('https://api.example.com', '/users')
    → 'https://api.example.com/users'
  • urlcat('https://api.example.com/', '/users')
    → 'https://api.example.com/users'
  • urlcat('http://example.com/', '/users/:userId/posts/:postId/comments', { userId: 123, postId: 987, authorId: 456, limit: 10, offset: 120 })
    → 'http://example.com/users/123/posts/987/comments?authorId=456&limit=10&offset=120'

query: build the query string

Build a query string using the specified key-value pairs. Keys and values are escaped and then concatenated by the '&' character.

E.g:

paramsresult
{}''
{ query: 'some text' }'query=some%20text'
{ id: 42, 'comment-id': 86 }'id=42&comment-id=86'
{ id: 42, 'a name': 'a value' }'id=42&a%20name=a%20value'

subst: Substitute path parameters

Replace the parameter with the value in the template string. Templates may contain 0 or more parameter placeholders. A placeholder begins with a colon ( : ), followed by a parameter name that can only contain upper or lower case letters. Any placeholders found in the template will be replaced with the value under the corresponding key in params .

E.g

templateparamsresult
':id'{ id: 42 }'42'
'/users/:id'{ id: 42 }'/users/42'
'/users/:id/comments/:commentId'{ id: 42, commentId: 86 }'/users/42/comments/86'
'/users/:id'{ id: 42, foo: 'bar' }'/users/42'

join: join two strings with a delimiter

Concatenate the two parts with only one delimiter. If the delimiter occurs at the end of part1 or at the beginning of part2 , remove it and then use the delimiter to join the two parts.

E.g:

part1separatorpart2result
'first'',''second''first,second'
'first,'',''second'
'first'','',second'
'first,'','',second'

Github library address: https://github.com/balazsbotond/urlcat


杭州程序员张张
11.8k 声望6.7k 粉丝

Web/Flutter/独立开发者/铲屎官