Skip to content

Commit

Permalink
fix: prevent key value store from firing setKey for each open subscri…
Browse files Browse the repository at this point in the history
…ption (#5997)
  • Loading branch information
cngonzalez committed Mar 14, 2024
1 parent f4a4c33 commit c173ef0
Showing 1 changed file with 14 additions and 22 deletions.
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

0 comments on commit c173ef0

Please sign in to comment.