Skip to content

Commit

Permalink
enable typescript strict mode (#1010)
Browse files Browse the repository at this point in the history
* strict mode

* disbale strict in test

* merge master

* fix name
  • Loading branch information
promer94 committed Mar 9, 2021
1 parent 9f37400 commit 158792a
Show file tree
Hide file tree
Showing 6 changed files with 153 additions and 161 deletions.
58 changes: 29 additions & 29 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { dequal } from 'dequal/lite'
import { SWRConfiguration, RevalidatorOptions, Revalidator } from './types'
import { Configuration, RevalidatorOptions, Revalidator } from './types'
import Cache from './cache'
import webPreset from './libs/web-preset'

Expand All @@ -8,11 +8,11 @@ const cache = new Cache()

// error retry
function onErrorRetry(
_,
__,
config: SWRConfiguration,
_: unknown,
__: string,
config: Readonly<Required<Configuration>>,
revalidate: Revalidator,
opts: RevalidatorOptions
opts: Required<RevalidatorOptions>
): void {
if (!config.isDocumentVisible()) {
// if it's hidden, stop
Expand All @@ -28,7 +28,7 @@ function onErrorRetry(
}

// exponential backoff
const count = Math.min(opts.retryCount || 0, 8)
const count = Math.min(opts.retryCount, 8)
const timeout =
~~((Math.random() + 0.5) * (1 << count)) * config.errorRetryInterval
setTimeout(revalidate, timeout, opts)
Expand All @@ -39,36 +39,36 @@ function onErrorRetry(
// slow connection (<= 70Kbps)
const slowConnection =
typeof window !== 'undefined' &&
// @ts-ignore
navigator['connection'] &&
// @ts-ignore
['slow-2g', '2g'].indexOf(navigator['connection'].effectiveType) !== -1

// config
const defaultConfig: SWRConfiguration = Object.assign(
{
// events
onLoadingSlow: () => {},
onSuccess: () => {},
onError: () => {},
onErrorRetry,
const defaultConfig = {
// events
onLoadingSlow: () => {},
onSuccess: () => {},
onError: () => {},
onErrorRetry,

errorRetryInterval: (slowConnection ? 10 : 5) * 1000,
focusThrottleInterval: 5 * 1000,
dedupingInterval: 2 * 1000,
loadingTimeout: (slowConnection ? 5 : 3) * 1000,
errorRetryInterval: (slowConnection ? 10 : 5) * 1000,
focusThrottleInterval: 5 * 1000,
dedupingInterval: 2 * 1000,
loadingTimeout: (slowConnection ? 5 : 3) * 1000,

refreshInterval: 0,
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshWhenHidden: false,
refreshWhenOffline: false,
shouldRetryOnError: true,
suspense: false,
compare: dequal,
refreshInterval: 0,
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshWhenHidden: false,
refreshWhenOffline: false,
shouldRetryOnError: true,
suspense: false,
compare: dequal,

isPaused: () => false
},
webPreset
)
isPaused: () => false,
...webPreset
} as const

export { cache }
export default defaultConfig
2 changes: 1 addition & 1 deletion src/libs/web-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const isDocumentVisible = () => {
return true
}

const fetcher = url => fetch(url).then(res => res.json())
const fetcher = (url: string) => fetch(url).then(res => res.json())

const registerOnFocus = (cb: () => void) => {
if (
Expand Down
34 changes: 18 additions & 16 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
// Internal types

export type Fetcher<Data> = (...args: any) => Data | Promise<Data>

export type Configuration<
export interface Configuration<
Data = any,
Error = any,
Fn extends Fetcher<Data> = Fetcher<Data>
> = {
> {
errorRetryInterval: number
errorRetryCount?: number
loadingTimeout: number
Expand All @@ -26,19 +23,26 @@ export type Configuration<
isOnline: () => boolean
isDocumentVisible: () => boolean
isPaused: () => boolean
onLoadingSlow: (key: string, config: Configuration<Data, Error>) => void
onLoadingSlow: (
key: string,
config: Readonly<Required<Configuration<Data, Error>>>
) => void
onSuccess: (
data: Data,
key: string,
config: Configuration<Data, Error>
config: Readonly<Required<Configuration<Data, Error>>>
) => void
onError: (
err: Error,
key: string,
config: Readonly<Required<Configuration<Data, Error>>>
) => void
onError: (err: Error, key: string, config: Configuration<Data, Error>) => void
onErrorRetry: (
err: Error,
key: string,
config: Configuration<Data, Error>,
config: Readonly<Required<Configuration<Data, Error>>>,
revalidate: Revalidator,
revalidateOpts: RevalidatorOptions
revalidateOpts: Required<RevalidatorOptions>
) => void
registerOnFocus?: (cb: () => void) => void
registerOnReconnect?: (cb: () => void) => void
Expand All @@ -57,7 +61,7 @@ export type Updater<Data = any, Error = any> = (
) => boolean | Promise<boolean>
export type Trigger = (key: Key, shouldRevalidate?: boolean) => Promise<any>

type MutatorCallback<Data = any> = (
export type MutatorCallback<Data = any> = (
currentValue: undefined | Data
) => Promise<undefined | Data> | undefined | Data

Expand Down Expand Up @@ -116,7 +120,7 @@ export type responseInterface<Data, Error> = {
) => Promise<Data | undefined>
isValidating: boolean
}
export type SWRResponse<Data, Error> = {
export interface SWRResponse<Data, Error> {
data?: Data
error?: Error
revalidate: () => Promise<boolean>
Expand Down Expand Up @@ -159,10 +163,8 @@ export type SWRInfiniteResponseInterface<Data = any, Error = any> = SWRResponse<
size: number | ((size: number) => number)
) => Promise<Data[] | undefined>
}
export type SWRInfiniteResponse<Data = any, Error = any> = SWRResponse<
Data[],
Error
> & {
export interface SWRInfiniteResponse<Data = any, Error = any>
extends SWRResponse<Data[], Error> {
size: number
setSize: (
size: number | ((size: number) => number)
Expand Down
67 changes: 31 additions & 36 deletions src/use-swr-infinite.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// TODO: use @ts-expect-error
import { useContext, useRef, useState, useEffect, useCallback } from 'react'

import defaultConfig, { cache } from './config'
Expand All @@ -8,7 +9,8 @@ import {
ValueKey,
Fetcher,
SWRInfiniteConfiguration,
SWRInfiniteResponse
SWRInfiniteResponse,
MutatorCallback
} from './types'

type KeyLoader<Data = any> = (
Expand All @@ -17,51 +19,44 @@ type KeyLoader<Data = any> = (
) => ValueKey

function useSWRInfinite<Data = any, Error = any>(
getKey: KeyLoader<Data>
): SWRInfiniteResponse<Data, Error>
function useSWRInfinite<Data = any, Error = any>(
getKey: KeyLoader<Data>,
config?: Partial<SWRInfiniteConfiguration<Data, Error>>
): SWRInfiniteResponse<Data, Error>
function useSWRInfinite<Data = any, Error = any>(
getKey: KeyLoader<Data>,
fn?: Fetcher<Data>,
config?: Partial<SWRInfiniteConfiguration<Data, Error>>
): SWRInfiniteResponse<Data, Error>
function useSWRInfinite<Data = any, Error = any>(
getKey: KeyLoader<Data>,
...options: any[]
...args:
| readonly [KeyLoader<Data>]
| readonly [KeyLoader<Data>, Fetcher<Data>]
| readonly [KeyLoader<Data>, SWRInfiniteConfiguration<Data, Error>]
| readonly [
KeyLoader<Data>,
Fetcher<Data>,
SWRInfiniteConfiguration<Data, Error>
]
): SWRInfiniteResponse<Data, Error> {
let _fn: Fetcher<Data> | undefined,
_config: Partial<SWRInfiniteConfiguration<Data, Error>> = {}

if (options.length > 1) {
_fn = options[0]
_config = options[1]
} else {
if (typeof options[0] === 'function') {
_fn = options[0]
} else if (typeof options[0] === 'object') {
_config = options[0]
}
}
const getKey = args[0]

const config: SWRInfiniteConfiguration<Data, Error> = Object.assign(
const config = Object.assign(
{},
defaultConfig,
useContext(SWRConfigContext),
_config
args.length > 2
? args[2]
: args.length === 2 && typeof args[1] === 'object'
? args[1]
: {}
)
let {
// in typescript args.length > 2 is not same as args.lenth === 3
// we do a safe type assertion here
// args.length === 3
const fn = (args.length > 2
? args[1]
: args.length === 2 && typeof args[1] === 'function'
? args[1]
: config.fetcher) as Fetcher<Data>

const {
initialSize = 1,
revalidateAll = false,
persistSize = false,
fetcher: defaultFetcher,
...extraConfig
} = config

const fn = typeof _fn !== 'undefined' ? _fn : defaultFetcher

// get the serialized key of the first page
let firstPageKey: string | null = null
try {
Expand Down Expand Up @@ -172,7 +167,7 @@ function useSWRInfinite<Data = any, Error = any>(
}, [swr.data])

const mutate = useCallback(
(data, shouldRevalidate = true) => {
(data: MutatorCallback, shouldRevalidate = true) => {
if (shouldRevalidate && typeof data !== 'undefined') {
// we only revalidate the pages that are changed
const originalData = dataRef.current
Expand Down Expand Up @@ -228,7 +223,7 @@ function useSWRInfinite<Data = any, Error = any>(
enumerable: true
}
})
return swrInfinite as SWRInfiniteResponse<Data, Error>
return (swrInfinite as unknown) as SWRInfiniteResponse<Data, Error>
}

export { useSWRInfinite }
Loading

0 comments on commit 158792a

Please sign in to comment.