resolve-args.ts


Overview

The resolve-args.ts file provides a higher-order function withArgs designed to enhance SWR (stale-while-revalidate) hooks by standardizing argument handling, configuration merging, and middleware application. It acts as a utility wrapper that normalizes input arguments, combines user and default configurations, and applies a chain of middleware functions before invoking the original hook.

This abstraction enables consistent hook usage patterns and centralized middleware management, simplifying the creation of customized SWR hooks with flexible configuration and behavior enhancements.


Exports

withArgs

export const withArgs = <SWRType>(hook: any) => {
  return function useSWRArgs(...args: any): SWRType
}

Description

withArgs is a higher-order function that accepts an SWR hook and returns a new hook function. The returned hook:

This pattern abstracts away argument handling and middleware application, enabling consistent, composable SWR hook usage.

Type Parameters

Parameters

Returns

Usage Example

import useSWR from 'swr'
import { withArgs } from './resolve-args'

const useCustomSWR = withArgs<typeof useSWR>(useSWR)

// Usage of the wrapped hook:
const { data, error } = useCustomSWR('/api/data', fetcherFunction, { refreshInterval: 1000 })

Here, useCustomSWR behaves like useSWR but benefits from argument normalization, merged configs, and middleware execution.


Implementation Details

Argument Normalization

Configuration Merging

Middleware Application

Hook Invocation


Interactions with Other Modules

These imports collectively enable withArgs to normalize inputs, merge configs, and apply middleware transparently.


Diagram: Functional Flow of withArgs

flowchart TD
    A[Call wrapped hook: useSWRArgs(...args)] --> B[useSWRConfig() to get fallbackConfig]
    B --> C[normalize(args) → [key, fn, _config]]
    C --> D[mergeConfigs(fallbackConfig, _config) → config]
    D --> E[Extract middleware list: (config.use || []) + BUILT_IN_MIDDLEWARE]
    E --> F[Apply middleware pipeline to original hook]
    F --> G[Invoke composed hook: next(key, fn || config.fetcher || null, config)]
    G --> H[Return SWR response]

Summary

The resolve-args.ts file is a critical utility for creating enhanced SWR hooks that:

Its design promotes modularity, reusability, and configurability in SWR-based data fetching hooks, fitting into the larger system as a foundational building block for custom hooks and middleware enhancements.


If you require further details on the imported modules (merge-config, normalize-args, use-swr-config, middleware-preset), those files typically handle their respective concerns like config merging logic, argument parsing, global config state, and middleware definitions.