抓取 client 是一个小的, 键入的包装器周围 fetch 与JSON帮手,
中间软件、限制费率、断路器、超时和友好错误
处理.
特征
- 输入的 JSON 助手 - 说吧
getJSON, (中文(简体) ),queryJSON, (中文(简体) ),postJSON, (中文(简体) ),putJSON, (中文(简体) ),patchJSON, (中文(简体) ),deleteJSON - 两个 API 样式 - 功能或班级 - 你的选择
- 响应缓存 - 基于 TTL 的缓存, 带有分组无效标记
- 中间软件 - 拦截请求/答复记录、认证、转换
- 限制费率 - 具有自动信头探测器的域内费率限制
- 断路器 - 防止服务下降时出现连锁故障
- 超时 - 请求中止信号支持的超时
- 处理错误 - RFC 7807问题细节支持
- 测试 - 在测试中嘲弄HTTP的模拟记录
安装
npm install @foundatiofx/fetchclient
快速示例
Fettleclient 工作有两种方式 - 选择您喜欢的样式 :
函数 API
import { getJSON, postJSON, setBaseUrl } from "@foundatiofx/fetchclient";
setBaseUrl("https://api.example.com");
const { data: users } = await getJSON<User[]>("/users");
const { data: created } = await postJSON<User>("/users", { name: "Alice" });
或使用 getFetchClient() 避免多重进口:
import { getFetchClient, setBaseUrl } from "@foundatiofx/fetchclient";
setBaseUrl("https://api.example.com");
const client = getFetchClient();
const { data: users } = await client.getJSON<User[]>("/users");
const { data: created } = await client.postJSON<User>("/users", {
name: "Alice",
});
基于类的 API
import { FetchClient } from "@foundatiofx/fetchclient";
const client = new FetchClient({ baseUrl: "https://api.example.com" });
const { data } = await client.getJSON<User[]>("/users");
缓存
const response = await client.getJSON<User>("/api/users/1", {
cacheKey: ["users", "1"],
cacheDuration: 60000, // 1 minute
cacheTags: ["users"],
});
// Invalidate by tag
client.cache.deleteByTag("users");
中间软件
import { useMiddleware } from "@foundatiofx/fetchclient";
useMiddleware(async (ctx, next) => {
console.log("Request:", ctx.request.url);
await next();
console.log("Response:", ctx.response?.status);
});
限制费率
import { usePerDomainRateLimit } from "@foundatiofx/fetchclient";
usePerDomainRateLimit({
maxRequests: 100,
windowSeconds: 60,
updateFromHeaders: true, // Respect API rate limit headers
});
断路器
import { useCircuitBreaker } from "@foundatiofx/fetchclient";
useCircuitBreaker({
failureThreshold: 5,
openDurationMs: 30000,
});
// When API fails repeatedly, circuit opens
// Requests return 503 immediately without hitting the API
测试
import { FetchClientProvider } from "@foundatiofx/fetchclient";
import { MockRegistry } from "@foundatiofx/fetchclient/mocks";
const mocks = new MockRegistry();
mocks.onGet("/api/users").reply(200, [{ id: 1, name: "Alice" }]);
const client = new FetchClient();
mocks.install(client);
const { data } = await client.getJSON("/api/users");
// data = [{ id: 1, name: "Alice" }]
文档
- 指南实例( E) : https://fetchclient.foundatio.dev 页面存档备份,存于互联网档案馆
- API 参考 : https://jsr.io/@foundatiofx/fetch客户端/doc
麻省理工学院 创始人