Urlcat:JavaScript的URL構(gòu)建器庫
urlcat 是一個小型的 JavaScript 庫,它使構(gòu)建 URL 非常方便并防止常見錯誤。
特性:
- 友好的 API
- 無依賴
- 壓縮后0.8KB大小
- 提供TypeScript類型
為什么用?在調(diào)用 HTTP API 時,通常需要在 URL 中添加動態(tài)參數(shù):
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
}
正如你所看到的,這個最小的例子已經(jīng)很難閱讀了。這也是不正確的:
- 我忘記了 API_URL 常量末尾有一個斜杠,所以這導(dǎo)致了一個包含重復(fù)斜杠的 URL(https://api.example.com//users)
- 嵌入的值需要使用 encodeURIComponent 進(jìn)行轉(zhuǎn)義
我可以使用內(nèi)置的 URL 類來防止重復(fù)的斜杠和 URLSearchParams 來轉(zhuǎn)義查詢字符串。但我仍然需要手動轉(zhuǎn)義所有路徑參數(shù)。
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
}
如此簡單的任務(wù),卻又很難讀,寫也很乏味!這是這個小型庫可以幫助您的地方:
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
}
這個庫會這樣處理:
- 轉(zhuǎn)義所有參數(shù)
- 將所有部分連接起來(它們之間總是正好有一個/ 和 ?)
如何使用?目前,該軟件包通過 npm 分發(fā)。(Zip 下載和 CDN 即將推出)。
npm install --save urlcat
在Node.js中使用
官方支持 Node 10 及更高版本。由于代碼在內(nèi)部使用 URL 和 URLSearchParams 類,它們在 v10 以下不可用,因此我們無法支持這些版本。
要構(gòu)建完整的 URL(最常見的用例):
const urlcat = require('urlcat').default;
要使用任何一個實用函數(shù):
const { query, subst, join } = require('urlcat');
要使用所有導(dǎo)出的函數(shù):
const { default: urlcat, query, subst, join } = require('urlcat');
在Typescript中使用
官方支持 TypeScript 2.1 及更高版本。
要構(gòu)建完整的 URL(最常見的用例):
import urlcat from 'urlcat';
要使用任何一個實用函數(shù):
import { query, subst, join } from 'urlcat';
要使用所有導(dǎo)出的函數(shù):
import urlcat, { query, subst, join } from 'urlcat';
在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:具有字符串鍵的對象
例如,{ firstParam: 1, 'second-param': 2 } 是一個有效的 ParamMap。
urlcat:構(gòu)建完整的 URL
function urlcat(baseUrl: string, pathTemplate: string, params: ParamMap): string
function urlcat(baseUrl: string, pathTemplate: string): string
function urlcat(baseTemplate: string, params: ParamMap): string
例如:
- 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:構(gòu)建查詢字符串
使用指定的鍵值對構(gòu)建查詢字符串。鍵和值被轉(zhuǎn)義,然后由 '&' 字符連接。
例如:
? | result |
? | ? |
? | ? |
? | ? |
? | ? |
subst:替換路徑參數(shù)
用模板字符串中的值替換參數(shù)。模板可能包含 0 個或多個參數(shù)占位符。占位符以冒號 (:) 開頭,后跟只能包含大寫或小寫字母的參數(shù)名稱。在模板中找到的任何占位符都將替換為 params中相應(yīng)鍵下的值。
例如
? | ? | result |
? | ? | ? |
? | ? | ? |
? | ? | ? |
? | ? | ? |
join:使用一個分隔符連接兩個字符串
僅使用一個分隔符連接兩個部分。如果分隔符出現(xiàn)在 part1 的末尾或 part2 的開頭,則將其刪除,然后使用分隔符連接兩個部分。
例如:
|
|
| result |
|
|
|
|
|
|
| |
|
|
| |
|
|
|
Github庫地址:https://github.com/balazsbotond/urlcat