Skip to content

Commit

Permalink
refactor(structure): use rxSwr for listenSearchQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
bjoerge committed Sep 30, 2024
1 parent 332168b commit 751342b
Showing 1 changed file with 12 additions and 40 deletions.
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
import {type SanityClient} from '@sanity/client'
import QuickLRU from 'quick-lru'
import {
asyncScheduler,
defer,
EMPTY,
map,
merge,
mergeMap,
type Observable,
of,
type OperatorFunction,
partition,
pipe,
share,
take,
throttleTime,
throwError,
timer,
} from 'rxjs'
import {tap} from 'rxjs/operators'
import {exhaustMapWithTrailing} from 'rxjs-exhaustmap-with-trailing'
import {createSearch, getSearchableTypes, type SanityDocumentLike, type Schema} from 'sanity'
import {
createSearch,
createSWR,
getSearchableTypes,
type SanityDocumentLike,
type Schema,
} from 'sanity'

import {getExtendedProjection} from '../../structureBuilder/util/getExtendedProjection'
import {ENABLE_LRU_MEMO} from './constants'
import {type SortOrder} from './types'

interface ListenQueryOptions {
Expand All @@ -44,6 +44,8 @@ export interface SearchQueryResult {
documents: SanityDocumentLike[]
}

const swr = createSWR<SanityDocumentLike[]>({maxSize: 100})

export function listenSearchQuery(options: ListenQueryOptions): Observable<SearchQueryResult> {
const {
client,
Expand Down Expand Up @@ -91,7 +93,7 @@ export function listenSearchQuery(options: ListenQueryOptions): Observable<Searc

const [welcome$, mutationAndReconnect$] = partition(events$, (ev) => ev.type === 'welcome')

const memoKey = JSON.stringify({filter, limit, params, searchQuery, sort, staticTypeNames})
const swrKey = JSON.stringify({filter, limit, params, searchQuery, sort, staticTypeNames})

return merge(
welcome$.pipe(take(1)),
Expand Down Expand Up @@ -157,37 +159,7 @@ export function listenSearchQuery(options: ListenQueryOptions): Observable<Searc
}),
)
}),
ENABLE_LRU_MEMO
? pipe(
memoLRU(memoKey, lru),
map((memo) => ({
fromCache: memo.type === 'memo',
documents: memo.value,
})),
)
: map((documents) => ({
fromCache: false,
documents,
})),
swr(swrKey),
map(({fromCache, value}) => ({fromCache, documents: value})),
)
}

const lru = new QuickLRU<string, SanityDocumentLike[]>({maxSize: 100})
function memoLRU<T>(
memoKey: string,
cache: QuickLRU<string, T>,
): OperatorFunction<T, {type: 'memo'; value: T} | {type: 'value'; value: T}> {
return (input$: Observable<T>) =>
merge(
defer(() =>
cache.has(memoKey) ? of({type: 'memo' as const, value: cache.get(memoKey)!}) : EMPTY,
),
input$.pipe(
tap((result) => cache.set(memoKey, result)),
map((value) => ({
type: 'value' as const,
value: value,
})),
),
)
}

0 comments on commit 751342b

Please sign in to comment.