urlcat:JavaScript的URL构建器库

前端全栈开发者

共 3882字,需浏览 8分钟

 · 2022-02-14

urlcat 是一个小型的 JavaScript 库,它使构建 URL 非常方便并防止常见错误。

特性:

  • 友好的 API
  • 无依赖
  • 压缩后0.8KB大小
  • 提供TypeScript类型

为什么用?

在调用 HTTP API 时,通常需要在 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
}

正如你所看到的,这个最小的例子已经很难阅读了。这也是不正确的:

  • 我忘记了 API_URL 常量末尾有一个斜杠,所以这导致了一个包含重复斜杠的 URL(https://api.example.com//users)
  • 嵌入的值需要使用 encodeURIComponent 进行转义

我可以使用内置的 URL 类来防止重复的斜杠和 URLSearchParams 来转义查询字符串。但我仍然需要手动转义所有路径参数。

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
}

如此简单的任务,却又很难读,写也很乏味!这是这个小型库可以帮助您的地方:

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
}

这个库会这样处理:

  • 转义所有参数
  • 将所有部分连接起来(它们之间总是正好有一个 /?

如何使用?

目前,该软件包通过 npm 分发。(Zip 下载和 CDN 即将推出)。

npm install --save urlcat

在Node.js中使用

官方支持 Node 10 及更高版本。由于代码在内部使用 URL 和 URLSearchParams 类,它们在 v10 以下不可用,因此我们无法支持这些版本。

要构建完整的 URL(最常见的用例):

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

要使用任何一个实用函数:

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

要使用所有导出的函数:

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

在Typescript中使用

官方支持 TypeScript 2.1 及更高版本。

要构建完整的 URL(最常见的用例):

import urlcat from 'urlcat';

要使用任何一个实用函数:

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

要使用所有导出的函数:

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:构建完整的 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:构建查询字符串

使用指定的键值对构建查询字符串。键和值被转义,然后由 '&' 字符连接。

例如:

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:替换路径参数

用模板字符串中的值替换参数。模板可能包含 0 个或多个参数占位符。占位符以冒号 (:) 开头,后跟只能包含大写或小写字母的参数名称。在模板中找到的任何占位符都将替换为 params 中相应键下的值。

例如

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:使用一个分隔符连接两个字符串

仅使用一个分隔符连接两个部分。如果分隔符出现在 part1 的末尾或 part2 的开头,则将其删除,然后使用分隔符连接两个部分。

例如:

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

Github库地址:https://github.com/balazsbotond/urlcat

最新发布
浏览 34
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报