Skip to content

Middleware #1160

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jun 21, 2021
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/explicit-module-boundary-types": 0,
"react-hooks/rules-of-hooks": 2,
"react-hooks/exhaustive-deps": 1
"react-hooks/exhaustive-deps": 1,
"react/prop-types": "off"
}
}
25 changes: 21 additions & 4 deletions src/config-context.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
import { createContext } from 'react'
import { createContext, createElement, useContext, FC } from 'react'

import { SWRConfiguration } from './types'

const SWRConfigContext = createContext<SWRConfiguration>({})
SWRConfigContext.displayName = 'SWRConfig'
export const SWRConfigContext = createContext<SWRConfiguration>({})

export default SWRConfigContext
const SWRConfig: FC<{
value: SWRConfiguration
}> = ({ children, value }) => {
// Extend middlewares of parent config context.
const parentConfigContext = useContext(SWRConfigContext)
if (parentConfigContext && parentConfigContext.middlewares) {
value = {
...value,
middlewares: [
...parentConfigContext.middlewares,
...(value.middlewares || [])
]
}
}

return createElement(SWRConfigContext.Provider, { value }, children)
}

export default SWRConfig
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// `useSWR` and related APIs
import { default as useSWR } from './use-swr'
export { SWRConfig, mutate, createCache } from './use-swr'
export default useSWR
export * from './use-swr'

// `useSWRInfinite`
export { useSWRInfinite } from './use-swr-infinite'
export { default as useSWRInfinite } from './use-swr-infinite'

// Types
export {
Expand All @@ -17,6 +17,7 @@ export {
KeyLoader,
SWRResponse,
Cache,
Middleware,
// Legacy, for backwards compatibility
ConfigInterface,
SWRInfiniteConfigInterface,
Expand Down
59 changes: 45 additions & 14 deletions src/resolve-args.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,40 @@
import { useContext } from 'react'

import defaultConfig from './config'
import SWRConfigContext from './config-context'
import { SWRConfigContext } from './config-context'

import { Fetcher } from './types'
import { Fetcher, SWRConfiguration } from './types'

// Resolve arguments for SWR hooks.
// This function itself is a hook because it uses `useContext` inside.
export default function useArgs<KeyType, ConfigType, Data>(
function useArgs<KeyType, Data>(
args:
| readonly [KeyType]
| readonly [KeyType, Fetcher<Data> | null]
| readonly [KeyType, ConfigType | undefined]
| readonly [KeyType, Fetcher<Data> | null, ConfigType | undefined]
): [KeyType, Fetcher<Data> | null, (typeof defaultConfig) & ConfigType] {
const config = {
| readonly [KeyType, SWRConfiguration | undefined]
| readonly [KeyType, Fetcher<Data> | null, SWRConfiguration | undefined]
): [KeyType, Fetcher<Data> | null, (typeof defaultConfig) & SWRConfiguration] {
const fallbackConfig = {
...defaultConfig,
...useContext(SWRConfigContext),
...(args.length > 2
? args[2]
: args.length === 2 && typeof args[1] === 'object'
? args[1]
: {})
} as (typeof defaultConfig) & ConfigType
...useContext(SWRConfigContext)
}
const currentConfig = (args.length > 2
? args[2]
: args.length === 2 && typeof args[1] === 'object'
? args[1]
: {}) as (typeof defaultConfig) & SWRConfiguration
const config = {
...fallbackConfig,
...currentConfig
}

// Extend `middlewares`.
if (fallbackConfig.middlewares) {
config.middlewares = [
...fallbackConfig.middlewares,
...(currentConfig.middlewares || [])
]
}

// In TypeScript `args.length > 2` is not same as `args.lenth === 3`.
// We do a safe type assertion here.
Expand All @@ -38,3 +50,22 @@ export default function useArgs<KeyType, ConfigType, Data>(

return [args[0], fn, config]
}

// It's tricky to pass generic types as parameters, so we just directly override
// the types here.
export default function withArgs<SWRType>(hook: any) {
return (((...args: any) => {
const [key, fn, config] = useArgs<any, any>(args)

// Apply middlewares to the hook.
let next = hook
const { middlewares } = config
if (middlewares) {
for (let i = 0; i < middlewares.length; i++) {
next = middlewares[i](next)
}
}

return next(key, fn, config)
}) as unknown) as SWRType
}
15 changes: 15 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface Configuration<
fetcher: Fn
initialData?: Data
cache: Cache
middlewares?: Middleware[]

isPaused: () => boolean
onLoadingSlow: (
Expand Down Expand Up @@ -47,13 +48,27 @@ export interface Configuration<
compare: (a: Data | undefined, b: Data | undefined) => boolean
}

export type SWRHook = <Data = any, Error = any>(
...args:
| readonly [Key]
| readonly [Key, Fetcher<Data> | null]
| readonly [Key, SWRConfiguration<Data, Error> | undefined]
| readonly [
Key,
Fetcher<Data> | null,
SWRConfiguration<Data, Error> | undefined
]
) => SWRResponse<Data, Error>

export interface Preset {
isOnline: () => boolean
isDocumentVisible: () => boolean
registerOnFocus?: (cb: () => void) => void
registerOnReconnect?: (cb: () => void) => void
}

export type Middleware = (useSWRNext: SWRHook) => SWRHook

export type ValueKey = string | any[] | null

export type Updater<Data = any, Error = any> = (
Expand Down
47 changes: 24 additions & 23 deletions src/use-swr-infinite.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// TODO: use @ts-expect-error
import { useRef, useState, useCallback } from 'react'

import defaultConfig from './config'
import { useIsomorphicLayoutEffect } from './env'
import { serialize } from './libs/serialize'
import { isUndefined, UNDEFINED } from './libs/helper'
import useArgs from './resolve-args'
import useSWR from './use-swr'
import withArgs from './resolve-args'
import { useSWRHandler } from './use-swr'

import {
KeyLoader,
Expand All @@ -15,26 +16,11 @@ import {
MutatorCallback
} from './types'

function useSWRInfinite<Data = any, Error = any>(
...args:
| readonly [KeyLoader<Data>]
| readonly [KeyLoader<Data>, Fetcher<Data> | null]
| readonly [
KeyLoader<Data>,
SWRInfiniteConfiguration<Data, Error> | undefined
]
| readonly [
KeyLoader<Data>,
Fetcher<Data> | null,
SWRInfiniteConfiguration<Data, Error> | undefined
]
function useSWRInfiniteHandler<Data = any, Error = any>(
getKey: KeyLoader<Data>,
fn: Fetcher<Data> | null,
config: typeof defaultConfig & SWRInfiniteConfiguration<Data, Error>
): SWRInfiniteResponse<Data, Error> {
const [getKey, fn, config] = useArgs<
KeyLoader<Data>,
SWRInfiniteConfiguration<Data, Error>,
Data
>(args)

const {
cache,
initialSize = 1,
Expand Down Expand Up @@ -99,7 +85,7 @@ function useSWRInfinite<Data = any, Error = any>(
const dataRef = useRef<Data[]>()

// actual swr of all pages
const swr = useSWR<Data[], Error>(
const swr = useSWRHandler<Data[], Error>(
firstPageKey ? ['inf', firstPageKey] : null,
async () => {
// get the revalidate context
Expand Down Expand Up @@ -234,4 +220,19 @@ function useSWRInfinite<Data = any, Error = any>(
return (swrInfinite as unknown) as SWRInfiniteResponse<Data, Error>
}

export { useSWRInfinite }
type SWRInfiniteHook = <Data = any, Error = any>(
...args:
| readonly [KeyLoader<Data>]
| readonly [KeyLoader<Data>, Fetcher<Data> | null]
| readonly [
KeyLoader<Data>,
SWRInfiniteConfiguration<Data, Error> | undefined
]
| readonly [
KeyLoader<Data>,
Fetcher<Data> | null,
SWRInfiniteConfiguration<Data, Error> | undefined
]
) => SWRInfiniteResponse<Data, Error>

export default withArgs<SWRInfiniteHook>(useSWRInfiniteHandler)
Loading