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

fix: prevent key value store from firing setKey for each open subscri… #5997

Merged
merged 1 commit into from
Mar 14, 2024
Merged
Changes from all 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
36 changes: 14 additions & 22 deletions packages/sanity/src/core/store/key-value/KeyValueStore.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {type SanityClient} from '@sanity/client'
import {merge, Observable, Subject} from 'rxjs'
import {filter, map, switchMap} from 'rxjs/operators'
import {merge, type Observable, Subject} from 'rxjs'
import {filter, map, shareReplay, switchMap, take} from 'rxjs/operators'

import {serverBackend} from './backends/server'
import {type KeyValueStore, type KeyValueStoreValue} from './types'
Expand All @@ -12,14 +12,15 @@ export function createKeyValueStore({client}: {client: SanityClient}): KeyValueS
const setKey$ = new Subject<{key: string; value: KeyValueStoreValue}>()

const updates$ = setKey$.pipe(
switchMap((event) =>
storageBackend.setKey(event.key, event.value).pipe(
switchMap((event) => {
return storageBackend.setKey(event.key, event.value).pipe(
map((nextValue) => ({
key: event.key,
value: nextValue,
})),
),
),
)
}),
shareReplay(1),
)

const getKey = (key: string): Observable<KeyValueStoreValue> => {
Expand All @@ -33,27 +34,18 @@ export function createKeyValueStore({client}: {client: SanityClient}): KeyValueS
}

const setKey = (key: string, value: KeyValueStoreValue): Observable<KeyValueStoreValue> => {
setKey$.next({key, value})

/*
* The backend returns the result of the set operation, so we can just pass that along.
* Most utils do not use it (they will take advantage of local state first) but it reflects the
* backend function and could be useful for debugging.
*/
const response = new Observable<KeyValueStoreValue>((subscriber) => {
const subscription = storageBackend.setKey(key, value).subscribe({
next: (nextValue) => {
subscriber.next(nextValue as KeyValueStoreValue)
subscriber.complete()
},
//storageBackend should handle its own errors, we're just passing along the result.
error: (err) => {
subscriber.error(err)
},
})
return () => subscription.unsubscribe()
})

setKey$.next({key, value})
return response
return updates$.pipe(
filter((update) => update.key === key),
map((update) => update.value as KeyValueStoreValue),
take(1),
)
}

return {getKey, setKey}
Expand Down
Loading