@foolishandi_tech/request
v0.1.4
Published
HTTP request library wrapper - Pure utility library, no Tauri dependencies
Downloads
48
Maintainers
Readme
@foolishandi_tech/request
HTTP request library wrapper - Pure utility library with no Tauri dependencies. Works in any JavaScript environment (browser, Node.js, etc.).
Installation
npm install @foolishandi_tech/requestyarn add @foolishandi_tech/requestpnpm add @foolishandi_tech/requestUsage
Basic Usage
import { get, post, put, del, patch } from "@foolishandi_tech/request";
// GET request
const data = await get("/api/users");
// POST request
const result = await post("/api/users", { name: "John", age: 30 });
// PUT request
const updated = await put("/api/users/1", { name: "Jane" });
// DELETE request
await del("/api/users/1");
// PATCH request
const patched = await patch("/api/users/1", { age: 31 });Initialize with Configuration
import { initRequest, get, post } from "@foolishandi_tech/request";
// Initialize with base URL, authentication, and cache
initRequest({
baseURL: "https://api.example.com",
timeout: 30000,
retry: {
maxAttempts: 3,
delay: 1000,
},
headers: {
"Content-Type": "application/json",
},
getAuthToken: async () => {
// Get token from localStorage, sessionStorage, or any storage
return localStorage.getItem("auth_token");
},
onTokenExpired: async () => {
// Handle token expiration
localStorage.removeItem("auth_token");
window.location.href = "/login";
},
cache: {
enabled: true, // Enable response caching
ttl: 5 * 60 * 1000, // Cache TTL: 5 minutes (default)
maxSize: 100, // Maximum cache entries (default: 100)
},
});
// Now all requests will use this configuration
const users = await get("/users");Custom Headers
import { get } from "@foolishandi_tech/request";
const data = await get("/api/data", {
headers: {
"X-Custom-Header": "value",
},
});Error Handling
import { get } from "@foolishandi_tech/request";
try {
const data = await get("/api/users");
} catch (error) {
if (error.code === 401) {
// Unauthorized
console.error("Authentication failed");
} else if (error.code === 404) {
// Not found
console.error("Resource not found");
} else {
console.error("Request failed:", error.message);
}
}Advanced Usage
import { request, initRequest } from "@foolishandi_tech/request";
// Initialize with custom configuration
initRequest({
baseURL: "https://api.example.com",
timeout: 10000,
retry: {
maxAttempts: 5,
delay: 2000,
},
getAuthToken: () => {
// Custom token retrieval logic
return Promise.resolve(localStorage.getItem("token"));
},
onTokenExpired: () => {
// Custom token expiration handling
console.log("Token expired, redirecting to login...");
window.location.href = "/login";
},
});
// Use the request function directly
const response = await request("/api/data", {
method: "POST",
json: { key: "value" },
headers: {
"X-Custom-Header": "value",
},
});API
Functions
initRequest(config: RequestConfig)
Initialize the request instance with configuration.
Parameters:
config.baseURL- Base URL for all requestsconfig.timeout- Request timeout in milliseconds (default: 30000)config.retry- Retry configurationmaxAttempts- Maximum retry attempts (default: 3)delay- Delay between retries in milliseconds (default: 1000)
config.headers- Default headers for all requestsconfig.getAuthToken- Function to get authentication tokenconfig.onTokenExpired- Callback when token expires (401 error)
request<T>(url: string, options?: RequestOptions)
Make an HTTP request.
get<T>(url: string, options?: RequestOptions)
Make a GET request.
post<T>(url: string, data?: any, options?: RequestOptions)
Make a POST request.
put<T>(url: string, data?: any, options?: RequestOptions)
Make a PUT request.
del<T>(url: string, options?: RequestOptions)
Make a DELETE request.
patch<T>(url: string, data?: any, options?: RequestOptions)
Make a PATCH request.
clearRequestCache()
Clear the request instance cache to force recreation with current config.
clearResponseCache()
Clear all cached responses.
clearCachedResponse(url: string, options?: RequestOptions)
Clear a specific cached response.
getCacheStats()
Get cache statistics including size, max size, and entry details.
Response Caching
The library supports response caching for GET requests:
import {
initRequest,
get,
clearResponseCache,
getCacheStats,
} from "@foolishandi_tech/request";
// Enable caching in config
initRequest({
baseURL: "https://api.example.com",
cache: {
enabled: true,
ttl: 10 * 60 * 1000, // 10 minutes
maxSize: 50, // Max 50 cached responses
},
});
// First request - fetches from server
const users1 = await get("/users");
// Second request - returns from cache (if within TTL)
const users2 = await get("/users");
// Per-request cache control
const freshData = await get("/users", { useCache: false }); // Skip cache
// Clear all cache
clearResponseCache();
// Get cache statistics
const stats = getCacheStats();
console.log(`Cache size: ${stats.size}/${stats.maxSize}`);Features
- ✅ Pure utility library - No Tauri dependencies
- ✅ Works in browser, Node.js, and any JavaScript environment
- ✅ Response caching - Automatic caching for GET requests with TTL support
- ✅ Automatic retry on failure
- ✅ Request/response interceptors
- ✅ Automatic authentication token handling
- ✅ Token expiration handling
- ✅ Request ID generation for tracing
- ✅ TypeScript support
- ✅ Built on top of ky
Response Format
The library expects responses in the following format:
{
code: 0 | 200, // 0 or 200 indicates success
message?: string,
data: T
}If code is not 0 or 200, an error will be thrown with the message.
Error Format
Errors are thrown in the following format:
{
code: number, // HTTP status code
message: string, // Error message
status?: number, // HTTP status code (same as code)
data?: any // Additional error data
}