or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

errors.mdhooks.mdhttp-methods.mdindex.mdinstances.mdoptions.mdpagination.mdresponses.mdstreams.mdutilities.md
tile.json

utilities.mddocs/

Utility Functions

Helper functions for retry calculation and Link header parsing that provide additional functionality for advanced use cases.

Capabilities

Calculate Retry Delay

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:

  1. RetryError: Returns 1ms (immediate retry)
  2. Attempt limit exceeded: Returns 0 (no retry)
  3. Method not allowed: Returns 0 if HTTP method not in retry methods
  4. Error/Status not eligible: Returns 0 if error code or status code not in retry lists
  5. Retry-After header: Uses server-specified delay if present and within timeout
  6. 413 Payload Too Large: Returns 0 (no retry for payload size errors)
  7. Exponential backoff: min(2^(attempt-1) * 1000, backoffLimit) + randomNoise

Parse Link Header

Function 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:

  • Each link: <URL>; param1=value1; param2=value2
  • Multiple links separated by commas
  • URLs must be enclosed in angle brackets < >
  • Parameters are key=value pairs separated by semicolons

Common Link Relations:

RelationDescription
nextNext page in pagination
prevPrevious page in pagination
firstFirst page in pagination
lastLast page in pagination
selfCurrent resource
editEditable 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");

Type Definitions

/**
 * Import types for utility functions
 */
import {
  calculateRetryDelay,
  parseLinkHeader,
  type RetryObject,
  type LinkHeaderResult
} from "got";