Hyper Fetch

repository·main·Indexed 23 days ago

https://github.com/bettertyped/hyper-fetch

A type-safe API layer for TypeScript applications providing a consistent interface for REST, GraphQL, Firebase, WebSockets, and SSE. It features smart caching, prefetching for instant navigation, and a pluggable adapter system including support for Axios, Firebase, and Firebase Admin.

Tokens
161K
Snippets
459
Records
640
Agent score
79%

What's inside hyper-fetch

  1. Overview of Hyper Fetch

    main

    Hyper Fetch is a modern, open-source framework designed for request-based and real-time communication. It is built to eliminate boilerplate and streamline data handling across any TypeScript environment, including browsers, servers, and native platforms like React Native or Electron.

    Key characteristics include:

    • Environment Agnostic: The core library works in any JavaScript environment.
    • Modular Architecture: Uses core modules for communication and specialized packages for specific frameworks (e.g., React).
    • Integrated Logic: Unlike libraries where fetchers and hooks are detached (e.g., mixing Axios with React Query), Hyper Fetch integrates request logic with state management and hooks to provide a unified experience for tracking progress, caching, and SSR.
  2. Overview of HyperFlow

    main

    HyperFlow is a dedicated DevTools suite designed for the Hyper Fetch ecosystem. It serves as a command center for monitoring, debugging, and optimizing your application's network activity and cache.

    Key capabilities include:

    • Real-time Visualization: Monitor network and cache activity as it happens.
    • Request/Response Debugging: Use a detailed inspector to examine payloads and responses.
    • Performance Optimization: Identify bottlenecks and inefficient resource usage.
    • Resource Management: Control request queues and cache entries with fine-grained control.
  3. Overview of React Hyper Fetch

    main

    React Hyper Fetch is a data fetching library that adapts the core Hyper Fetch functionality to the React environment. It manages fetching, submitting, streaming, and queueing requests. It provides specialized hooks for both core and sockets subpackages.

    Requirements:

    • React 18+: Required because hooks use useSyncExternalStore for concurrent mode semantics, selective re-rendering, and tearing prevention.
    • Request Instance: You must have a previously prepared request to use the hooks.
  4. What is @hyper-fetch/firebase-admin?

    main

    @hyper-fetch/firebase-admin is a type-safe adapter for the Firebase Admin SDK. It allows developers to use the same HyperFetch request patterns on the server (Node.js) as they do on the client (browser).

    Key Features:

    • Unified API: Use the same typed patterns for both Firestore and Realtime Database.
    • Reliability: Leverages HyperFetch's queuing and automatic retry capabilities with backoff for backend services.
    • Full Type Safety: End-to-end typing for parameters, payloads, and responses for every database operation.
  5. Key features of the Hyper Fetch ESLint plugin

    main

    The eslint-plugin-hyper-fetch plugin provides several benefits for Hyper Fetch users:

    • Type-Safe Generics: Detects generic type errors that TypeScript may overlook.
    • Immediate Feedback: Surfaces type-related issues directly in your editor as you code.
    • Fewer Runtime Bugs: Prevents issues caused by incorrect type usage before they reach runtime.
    • Clear Error Messages: Provides actionable feedback to make debugging faster and easier.
  6. What is an Adapter in Hyper Fetch

    main

    The Adapter class is the core communication layer of Hyper Fetch. It abstracts how requests are executed, allowing you to switch between different transport protocols (like HTTP, GraphQL, or Firebase) without changing your request logic.

    Key responsibilities of an adapter include:

    • Handling network communication.
    • Mapping headers, payloads, endpoints, and query parameters.
    • Managing the request lifecycle (progress tracking, cancellation, and error handling).
    • Providing hooks to override default behaviors for advanced scenarios.
  7. What is the Client in Hyper Fetch?

    main

    The Client is the core abstraction in Hyper Fetch that manages the lifecycle and configuration of your server communication.

    Its primary responsibilities include:

    1. Request Building: Serving as the factory for all requests made within the application.
    2. Configuration Management: Acting as the single source of truth for default settings (like base URLs, headers, etc.).
    3. Middleware & Security: Managing interceptors and authentication logic.
    4. Sub-module Orchestration: Initializing core subsystems like queues, cache, and plugins.

    By using a Client instance, you ensure that all requests share a consistent configuration and that different parts of your application can maintain isolated connection logic by using different client instances.

  8. What is a Socket Adapter

    main

    An Adapter is a class that defines how Hyper Fetch communicates with a server. It is responsible for specifying how to send and receive data, handling errors, managing reconnections, and more.

    Hyper Fetch provides built-in adapters for common protocols, but also allows for custom implementations (e.g., for socket.io) by fulfilling the SocketAdapter TypeScript contract.

  9. Manage request queues with useSubmit and useQueue

    main

    Hyper-fetch provides request queuing to control request execution, which is useful for background tasks like multiple file uploads. This allows you to process requests sequentially or in parallel without blocking the UI, and provides controls to pause or resume the entire queue.

    To implement queuing, you use two primary hooks:

    1. useSubmit: Used to add requests to a queue. You must first enable queuing on your request definition using .setQueue(true).
    2. useQueue: Used to monitor and control the queue state for a specific request.

    Workflow

    • Enable Queuing: Call .setQueue(true) on your request instance.
    • Add to Queue: Use the submit function from useSubmit to add new items to the queue instead of executing them immediately.
    • Control the Queue: Use the stop and start functions from useQueue to pause and resume processing.
    // 1. Enable queuing on the request definition
    const { submit } = useSubmit(postFile.setQueue(true));
    
    // 2. Monitor and control the queue
    const { requests, stopped, stop, start } = useQueue(postFile);
    
    // 3. Add items to the queue
    const handleFileChange = (event) => {
      const files = Array.from(event.target.files);
      files.forEach((file) => {
        const formData = new FormData();
        formData.append("file", file);
        submit({ payload: formData });
      });
    };