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:
Normalizes incoming arguments into a standard
[key, fetcher, config]tuple usingnormalize.Retrieves the global and inherited SWR configuration using
useSWRConfig.Merges the normalized config with the fallback config via
mergeConfigs.Applies middleware functions specified in the merged config plus built-in middleware.
Invokes the original hook with the fully resolved parameters.
This pattern abstracts away argument handling and middleware application, enabling consistent, composable SWR hook usage.
Type Parameters
SWRType: The expected type signature of the SWR hook being wrapped. Since TypeScript generics cannot be passed as runtime parameters, the function forcibly casts the returned function to this type.
Parameters
hook: any— The original SWR hook function to be wrapped. Typically a function likeuseSWR.
Returns
A new SWR hook function with the signature
(...args: any) => SWRTypethat performs argument normalization, config merging, middleware application, and finally calls the original hook.
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
Uses the imported
normalizefunction to convert arbitrary arguments into a normalized tuple:const [key, fn, _config] = normalize<any, any>(args)This ensures consistent handling regardless of how the user calls the hook.
Configuration Merging
Retrieves fallback or inherited configuration via
useSWRConfig().Merges the fallback config with the user-provided config (
_config) usingmergeConfigs.The merged config consolidates settings such as fetchers, middleware, and options.
Middleware Application
Extracts the
usearray from the merged config, representing user-defined middleware.Concatenates built-in middleware from
BUILT_IN_MIDDLEWARE.Applies all middleware functions in reverse order, composing them around the original hook:
let next = hook const middleware = (use || []).concat(BUILT_IN_MIDDLEWARE) for (let i = middleware.length; i--; ) { next = middleware[i](next) }This effectively creates a middleware pipeline where each middleware wraps the next, allowing pre/post-processing of hook calls.
Hook Invocation
Finally, the composed hook (
next) is invoked with:key— the normalized cache key.fn— the fetcher function, falling back toconfig.fetcherornull.config— the merged configuration object.
Interactions with Other Modules
merge-config: ProvidesmergeConfigsto combine multiple configuration objects, ensuring coherent and predictable config precedence.normalize-args: Providesnormalize, a utility that standardizes hook arguments into a uniform tuple.use-swr-config: SuppliesuseSWRConfig, a React hook giving access to global or inherited SWR configuration.middleware-preset: ExportsBUILT_IN_MIDDLEWARE, an array of default middleware functions automatically applied to all hooks wrapped bywithArgs.
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:
Normalize arguments for consistent API usage.
Combine global and local configurations robustly.
Integrate middleware in a flexible and composable manner.
Maintain type compatibility via generic casting.
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.