Human-friendly and powerful HTTP request library for Node.js
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Helper functions for retry calculation and Link header parsing that provide additional functionality for advanced use cases.
Function for calculating the delay before retrying a failed request, used internally by Got's retry mechanism and available for custom retry logic.
/**
* Calculate delay before retrying a failed request
* @param retryObject - Object containing retry information
* @returns Delay in milliseconds (0 means don't retry)
*/
function calculateRetryDelay(retryObject: RetryObject): number;
/**
* Retry calculation input object
*/
interface RetryObject {
/**
* Current attempt number (1-based)
*/
attemptCount: number;
/**
* Retry configuration options
*/
retryOptions: RetryOptions;
/**
* The error that triggered the retry
*/
error: RequestError;
/**
* Retry-After header value in seconds (if present)
*/
retryAfter?: number;
/**
* Computed timeout value
*/
computedValue: number;
}
/**
* Retry configuration options
*/
interface RetryOptions {
/**
* Maximum number of retry attempts
*/
limit: number;
/**
* HTTP methods that can be retried
*/
methods: string[];
/**
* HTTP status codes that trigger retries
*/
statusCodes: number[];
/**
* Error codes that trigger retries
*/
errorCodes: string[];
/**
* Maximum retry delay (exponential backoff limit)
*/
backoffLimit: number;
/**
* Random noise added to delay calculation
*/
noise: number;
}Usage Examples:
import { calculateRetryDelay } from "got";
// Custom retry logic
const retryObject = {
attemptCount: 2,
retryOptions: {
limit: 3,
methods: ["GET", "POST"],
statusCodes: [429, 500, 502, 503, 504],
errorCodes: ["ECONNRESET", "ETIMEDOUT"],
backoffLimit: 10000,
noise: 100
},
error: new RequestError("Connection timeout", { code: "ETIMEDOUT" }, options),
computedValue: 30000
};
const delay = calculateRetryDelay(retryObject);
console.log(`Wait ${delay}ms before retry`);
if (delay > 0) {
setTimeout(() => {
// Retry the request
retryRequest();
}, delay);
}Delay Calculation Logic:
The function implements the following retry logic:
min(2^(attempt-1) * 1000, backoffLimit) + randomNoiseFunction for parsing HTTP Link headers according to RFC 5988, commonly used for pagination in REST APIs.
/**
* Parse HTTP Link header into structured format
* @param header - Link header value from HTTP response
* @returns Array of parsed link objects
* @throws Error if header format is invalid
*/
function parseLinkHeader(header: string): LinkHeaderResult[];
/**
* Parsed Link header result
*/
interface LinkHeaderResult {
/**
* The URL reference (without angle brackets)
*/
reference: string;
/**
* Link parameters (rel, type, etc.)
*/
parameters: Record<string, string>;
}Usage Examples:
import { parseLinkHeader } from "got";
// Parse GitHub API Link header
const linkHeader = '</repos/user/repo/issues?page=2>; rel="next", </repos/user/repo/issues?page=5>; rel="last"';
const links = parseLinkHeader(linkHeader);
console.log(links);
// [
// {
// reference: "/repos/user/repo/issues?page=2",
// parameters: { rel: "next" }
// },
// {
// reference: "/repos/user/repo/issues?page=5",
// parameters: { rel: "last" }
// }
// ]
// Extract specific link relationships
const nextLink = links.find(link => link.parameters.rel === '"next"');
const lastLink = links.find(link => link.parameters.rel === '"last"');
if (nextLink) {
console.log("Next page URL:", nextLink.reference);
}Link Header Format:
The function parses Link headers following RFC 5988 format:
<URL>; param1=value1; param2=value2< >Common Link Relations:
| Relation | Description |
|---|---|
next | Next page in pagination |
prev | Previous page in pagination |
first | First page in pagination |
last | Last page in pagination |
self | Current resource |
edit | Editable version of resource |
Error Handling:
import { parseLinkHeader } from "got";
try {
const links = parseLinkHeader('invalid-format');
} catch (error) {
console.error("Invalid Link header format:", error.message);
// Handle parsing error gracefully
}
// Safe parsing with fallback
function safeParseLinkHeader(header?: string) {
if (!header) return [];
try {
return parseLinkHeader(header);
} catch (error) {
console.warn("Failed to parse Link header:", error.message);
return [];
}
}Integration with Pagination:
import got, { parseLinkHeader } from "got";
async function fetchAllPages(url: string) {
const allData = [];
let currentUrl = url;
while (currentUrl) {
const response = await got(currentUrl);
const data = JSON.parse(response.body);
allData.push(...data);
// Parse Link header for next page
const linkHeader = response.headers.link;
if (linkHeader) {
const links = parseLinkHeader(linkHeader);
const nextLink = links.find(link =>
link.parameters.rel === '"next"'
);
currentUrl = nextLink?.reference || null;
} else {
currentUrl = null;
}
}
return allData;
}
// Usage
const allIssues = await fetchAllPages("https://api.github.com/repos/owner/repo/issues");/**
* Import types for utility functions
*/
import {
calculateRetryDelay,
parseLinkHeader,
type RetryObject,
type LinkHeaderResult
} from "got";