Skip to content

Commit

Permalink
fix(structure): memoize search query results
Browse files Browse the repository at this point in the history
  • Loading branch information
bjoerge committed Sep 26, 2024
1 parent 4fc46c4 commit 79b46e0
Showing 1 changed file with 11 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {type SanityClient} from '@sanity/client'
import QuickLRU from 'quick-lru'
import {
asyncScheduler,
defer,
EMPTY,
map,
merge,
mergeMap,
Expand All @@ -14,6 +16,7 @@ import {
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'

Expand All @@ -34,6 +37,7 @@ interface ListenQueryOptions {
maxFieldDepth?: number
enableLegacySearch?: boolean
}
const lru = new QuickLRU<string, SanityDocumentLike[]>({maxSize: 1000})

export function listenSearchQuery(options: ListenQueryOptions): Observable<SanityDocumentLike[]> {
const {
Expand Down Expand Up @@ -82,6 +86,8 @@ export function listenSearchQuery(options: ListenQueryOptions): Observable<Sanit

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

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

return merge(
welcome$.pipe(take(1)),
mutationAndReconnect$.pipe(throttleTime(1000, asyncScheduler, {leading: true, trailing: true})),
Expand Down Expand Up @@ -146,5 +152,10 @@ export function listenSearchQuery(options: ListenQueryOptions): Observable<Sanit
}),
)
}),
tap((result) => lru.set(memoKey, result)),
(input$) =>
defer(() => {
return merge(lru.has(memoKey) ? of(lru.get(memoKey)!) : EMPTY, input$)
}),
)
}

0 comments on commit 79b46e0

Please sign in to comment.