@foundatiofx/fetchclient
v1.3.4
Published
 ;
const { data: users } = await getJSON<User[]>("/users");
const { data: created } = await postJSON<User>("/users", { name: "Alice" });Or use getFetchClient() to avoid multiple imports:
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",
});Class-Based API
import { FetchClient } from "@foundatiofx/fetchclient";
const client = new FetchClient({ baseUrl: "https://api.example.com" });
const { data } = await client.getJSON<User[]>("/users");Caching
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");Middleware
import { useMiddleware } from "@foundatiofx/fetchclient";
useMiddleware(async (ctx, next) => {
console.log("Request:", ctx.request.url);
await next();
console.log("Response:", ctx.response?.status);
});Rate Limiting
import { usePerDomainRateLimit } from "@foundatiofx/fetchclient";
usePerDomainRateLimit({
maxRequests: 100,
windowSeconds: 60,
updateFromHeaders: true, // Respect API rate limit headers
});Circuit Breaker
import { useCircuitBreaker } from "@foundatiofx/fetchclient";
useCircuitBreaker({
failureThreshold: 5,
openDurationMs: 30000,
});
// When API fails repeatedly, circuit opens
// Requests return 503 immediately without hitting the APITesting
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" }]Documentation
- Guide & Examples: https://fetchclient.foundatio.dev
- API Reference: https://jsr.io/@foundatiofx/fetchclient/doc
MIT © Foundatio
