Skip to content
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

feat: mutate filter #1989

Merged
merged 22 commits into from
Jun 26, 2022
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 13 additions & 10 deletions _internal/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ export type State<Data = any, Error = any> = {
error?: Error
isValidating?: boolean
isLoading?: boolean
key?: Key
}

export type MutatorFn<Data = any> = (
Expand All @@ -204,27 +205,28 @@ export type MutatorWrapper<Fn> = Fn extends (
export type Mutator<Data = any> = MutatorWrapper<MutatorFn<Data>>

export interface ScopedMutator<Data = any> {
/** This is used for bound mutator */
(
key: Key,
data?: Data | Promise<Data> | MutatorCallback<Data>,
<T = Data>(
match: (key: string) => boolean,
data?: T | Promise<T> | MutatorCallback<T>,
opts?: boolean | MutatorOptions<Data>
): Promise<Data | undefined>
/** This is used for global mutator */
<T = any>(
key: Key,
): Promise<Array<T | undefined>>
<T = Data>(
match: Arguments,
data?: T | Promise<T> | MutatorCallback<T>,
opts?: boolean | MutatorOptions<Data>
): Promise<T | undefined>
<T = Data>(
match: ((key: string) => boolean) | Arguments,
data?: T | Promise<T> | MutatorCallback<T>,
opts?: boolean | MutatorOptions<Data>
): Promise<any>
}

export type KeyedMutator<Data> = (
data?: Data | Promise<Data> | MutatorCallback<Data>,
opts?: boolean | MutatorOptions<Data>
) => Promise<Data | undefined>

// Public types

export type SWRConfiguration<
Data = any,
Error = any,
Expand Down Expand Up @@ -267,6 +269,7 @@ export type RevalidateCallback = <K extends RevalidateEvent>(
) => RevalidateCallbackReturnType[K]

export interface Cache<Data = any> {
values(): IterableIterator<State<Data, any>>
get(key: Key): State<Data> | undefined
set(key: Key, value: State<Data>): void
delete(key: Key): void
Expand Down
1 change: 1 addition & 0 deletions _internal/utils/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export const initCache = <Data = any>(
// If there's no global state bound to the provider, create a new one with the
// new mutate function.
const EVENT_REVALIDATORS = {}

const mutate = internalMutate.bind(
UNDEFINED,
provider
Expand Down
21 changes: 14 additions & 7 deletions _internal/utils/helper.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { SWRGlobalState } from './global-state'
import { Key, Cache, State, GlobalState } from '../types'
import type { Key, Cache, State, GlobalState } from '../types'

const EMPTY_CACHE = {}
export const noop = () => {}

// Using noop() as the undefined value as undefined can possibly be replaced
Expand All @@ -13,9 +12,16 @@ export const UNDEFINED = (/*#__NOINLINE__*/ noop()) as undefined
export const OBJECT = Object

export const isUndefined = (v: any): v is undefined => v === UNDEFINED
export const isFunction = (v: any): v is Function => typeof v == 'function'
export const isEmptyCache = (v: any): boolean => v === EMPTY_CACHE
export const isFunction = <
T extends (...args: any[]) => any = (...args: any[]) => any
>(
v: unknown
): v is T => typeof v == 'function'
export const mergeObjects = (a: any, b: any) => OBJECT.assign({}, a, b)
export const isEmptyCacheState = (v: State<any, any>): boolean => {
const keys = Object.keys(v)
return keys.length === 1 && keys[0] === 'key'
}

const STR_UNDEFINED = 'undefined'

Expand All @@ -30,13 +36,14 @@ export const createCacheHelper = <Data = any, T = State<Data, any>>(
key: Key
) => {
const state = SWRGlobalState.get(cache) as GlobalState
const emptyCache = { key }
return [
// Getter
() => (cache.get(key) || EMPTY_CACHE) as T,
() => (cache.get(key) || emptyCache) as T,
// Setter
(info: T) => {
const prev = cache.get(key)
state[5](key as string, mergeObjects(prev, info), prev || EMPTY_CACHE)
const prev = cache.get(key) || emptyCache
state[5](key as string, mergeObjects(prev, info), prev)
},
// Subscriber
state[6]
Expand Down
249 changes: 137 additions & 112 deletions _internal/utils/mutate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,41 @@ import { SWRGlobalState } from './global-state'
import { getTimestamp } from './timestamp'
import * as revalidateEvents from '../constants'
import {
Key,
Cache,
MutatorCallback,
MutatorOptions,
GlobalState,
State
State,
Arguments,
Key
} from '../types'

export const internalMutate = async <Data>(
type KeyFilter = (key?: Key) => boolean
type MutateState<Data> = State<Data, any> & {
// The previously committed data.
_c?: Data
}

export async function internalMutate<Data>(
cache: Cache,
_key: KeyFilter,
_data?: Data | Promise<Data | undefined> | MutatorCallback<Data>,
_opts?: boolean | MutatorOptions<Data>
): Promise<Array<Data | undefined>>
export async function internalMutate<Data>(
cache: Cache,
_key: Arguments,
_data?: Data | Promise<Data | undefined> | MutatorCallback<Data>,
_opts?: boolean | MutatorOptions<Data>
): Promise<Data | undefined>
export async function internalMutate<Data>(
...args: [
Cache,
Key,
undefined | Data | Promise<Data | undefined> | MutatorCallback<Data>,
undefined | boolean | MutatorOptions<Data>
cache: Cache,
_key: KeyFilter | Arguments,
_data?: Data | Promise<Data | undefined> | MutatorCallback<Data>,
_opts?: boolean | MutatorOptions<Data>
]
): Promise<Data | undefined> => {
): Promise<any> {
const [cache, _key, _data, _opts] = args

// When passing as a boolean, it's explicitly used to disable/enable
Expand All @@ -35,130 +54,136 @@ export const internalMutate = async <Data>(
const revalidate = options.revalidate !== false
const rollbackOnError = options.rollbackOnError !== false

// Serialize key
const [key] = serialize(_key)
if (!key) return

const [get, set] = createCacheHelper<
Data,
State<Data, any> & {
// The previously committed data.
_c?: Data
// If 2nd arg is key filter, return the mutation results of filtered keys
if (isFunction(_key)) {
const keyFilter = _key
const matchedKeys: Key[] = []
for (const state of cache.values()) {
huozhi marked this conversation as resolved.
Show resolved Hide resolved
if (keyFilter(state.key)) matchedKeys.push(state.key)
}
>(cache, key)
const [EVENT_REVALIDATORS, MUTATION, FETCH] = SWRGlobalState.get(
cache
) as GlobalState

const revalidators = EVENT_REVALIDATORS[key]
const startRevalidate = () => {
if (revalidate) {
// Invalidate the key by deleting the concurrent request markers so new
// requests will not be deduped.
delete FETCH[key]
if (revalidators && revalidators[0]) {
return revalidators[0](revalidateEvents.MUTATE_EVENT).then(
() => get().data
)
return await Promise.all(matchedKeys.map(mutateByKey))
}
return await mutateByKey(_key)

async function mutateByKey(_k: Key): Promise<Data | undefined> {
// Serialize key
const [key] = serialize(_k)
if (!key) return
const [get, set] = createCacheHelper<Data, MutateState<Data>>(cache, key)
const [EVENT_REVALIDATORS, MUTATION, FETCH] = SWRGlobalState.get(
cache
) as GlobalState

const revalidators = EVENT_REVALIDATORS[key]
const startRevalidate = () => {
if (revalidate) {
// Invalidate the key by deleting the concurrent request markers so new
// requests will not be deduped.
delete FETCH[key]
if (revalidators && revalidators[0]) {
return revalidators[0](revalidateEvents.MUTATE_EVENT).then(
() => get().data
)
}
}
return get().data
}
return get().data
}

// If there is no new data provided, revalidate the key with current state.
if (args.length < 3) {
// Revalidate and broadcast state.
return startRevalidate()
}
// If there is no new data provided, revalidate the key with current state.
if (args.length < 3) {
// Revalidate and broadcast state.
return startRevalidate()
}

let data: any = _data
let error: unknown
let data: any = _data
let error: unknown

// Update global timestamps.
const beforeMutationTs = getTimestamp()
MUTATION[key] = [beforeMutationTs, 0]
// Update global timestamps.
const beforeMutationTs = getTimestamp()
MUTATION[key] = [beforeMutationTs, 0]

const hasOptimisticData = !isUndefined(optimisticData)
const state = get()
const hasOptimisticData = !isUndefined(optimisticData)
const state = get()

// `displayedData` is the current value on screen. It could be the optimistic value
// that is going to be overridden by a `committedData`, or get reverted back.
// `committedData` is the validated value that comes from a fetch or mutation.
const displayedData = state.data
const committedData = isUndefined(state._c) ? displayedData : state._c
// `displayedData` is the current value on screen. It could be the optimistic value
// that is going to be overridden by a `committedData`, or get reverted back.
// `committedData` is the validated value that comes from a fetch or mutation.
const displayedData = state.data
const committedData = isUndefined(state._c) ? displayedData : state._c

// Do optimistic data update.
if (hasOptimisticData) {
optimisticData = isFunction(optimisticData)
? optimisticData(committedData)
: optimisticData
// Do optimistic data update.
if (hasOptimisticData) {
optimisticData = isFunction(optimisticData)
? optimisticData(committedData)
: optimisticData

// When we set optimistic data, backup the current committedData data in `_c`.
set({ data: optimisticData, _c: committedData })
}
// When we set optimistic data, backup the current committedData data in `_c`.
set({ data: optimisticData, _c: committedData })
}

if (isFunction(data)) {
// `data` is a function, call it passing current cache value.
try {
data = (data as MutatorCallback<Data>)(committedData)
} catch (err) {
// If it throws an error synchronously, we shouldn't update the cache.
error = err
if (isFunction(data)) {
// `data` is a function, call it passing current cache value.
try {
data = (data as MutatorCallback<Data>)(committedData)
} catch (err) {
// If it throws an error synchronously, we shouldn't update the cache.
error = err
}
}
}

// `data` is a promise/thenable, resolve the final data first.
if (data && isFunction((data as Promise<Data>).then)) {
// This means that the mutation is async, we need to check timestamps to
// avoid race conditions.
data = await (data as Promise<Data>).catch(err => {
error = err
})

// Check if other mutations have occurred since we've started this mutation.
// If there's a race we don't update cache or broadcast the change,
// just return the data.
if (beforeMutationTs !== MUTATION[key][0]) {
if (error) throw error
return data
} else if (error && hasOptimisticData && rollbackOnError) {
// Rollback. Always populate the cache in this case but without
// transforming the data.
populateCache = true
data = committedData

// Reset data to be the latest committed data, and clear the `_c` value.
set({ data, _c: UNDEFINED })
// `data` is a promise/thenable, resolve the final data first.
if (data && isFunction((data as Promise<Data>).then)) {
// This means that the mutation is async, we need to check timestamps to
// avoid race conditions.
data = await (data as Promise<Data>).catch(err => {
error = err
})

// Check if other mutations have occurred since we've started this mutation.
// If there's a race we don't update cache or broadcast the change,
// just return the data.
if (beforeMutationTs !== MUTATION[key][0]) {
if (error) throw error
return data
} else if (error && hasOptimisticData && rollbackOnError) {
// Rollback. Always populate the cache in this case but without
// transforming the data.
populateCache = true
data = committedData

// Reset data to be the latest committed data, and clear the `_c` value.
set({ data, _c: UNDEFINED })
}
}
}

// If we should write back the cache after request.
if (populateCache) {
if (!error) {
// Transform the result into data.
if (isFunction(populateCache)) {
data = populateCache(data, committedData)
// If we should write back the cache after request.
if (populateCache) {
if (!error) {
// Transform the result into data.
if (isFunction(populateCache)) {
data = populateCache(data, committedData)
}

// Only update cached data if there's no error. Data can be `undefined` here.
set({ data, _c: UNDEFINED })
}

// Only update cached data if there's no error. Data can be `undefined` here.
set({ data, _c: UNDEFINED })
// Always update error and original data here.
set({ error })
}

// Always update error and original data here.
set({ error })
}

// Reset the timestamp to mark the mutation has ended.
MUTATION[key][1] = getTimestamp()
// Reset the timestamp to mark the mutation has ended.
MUTATION[key][1] = getTimestamp()

// Update existing SWR Hooks' internal states:
const res = await startRevalidate()
// Update existing SWR Hooks' internal states:
const res = await startRevalidate()

// The mutation and revalidation are ended, we can clear it since the data is
// not an optimistic value anymore.
set({ _c: UNDEFINED })
// The mutation and revalidation are ended, we can clear it since the data is
// not an optimistic value anymore.
set({ _c: UNDEFINED })

// Throw error or return data
if (error) throw error
return populateCache ? res : data
// Throw error or return data
if (error) throw error
return populateCache ? res : data
}
}