From 751342bf74b95ca692e876549de56ac3c5b347a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rge=20N=C3=A6ss?= Date: Thu, 26 Sep 2024 15:16:28 +0200 Subject: [PATCH] refactor(structure): use rxSwr for listenSearchQuery --- .../panes/documentList/listenSearchQuery.ts | 52 +++++-------------- 1 file changed, 12 insertions(+), 40 deletions(-) diff --git a/packages/sanity/src/structure/panes/documentList/listenSearchQuery.ts b/packages/sanity/src/structure/panes/documentList/listenSearchQuery.ts index f7aafc97684..2c0dcbe5dc9 100644 --- a/packages/sanity/src/structure/panes/documentList/listenSearchQuery.ts +++ b/packages/sanity/src/structure/panes/documentList/listenSearchQuery.ts @@ -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 { @@ -44,6 +44,8 @@ export interface SearchQueryResult { documents: SanityDocumentLike[] } +const swr = createSWR({maxSize: 100}) + export function listenSearchQuery(options: ListenQueryOptions): Observable { const { client, @@ -91,7 +93,7 @@ export function listenSearchQuery(options: ListenQueryOptions): Observable 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)), @@ -157,37 +159,7 @@ export function listenSearchQuery(options: ListenQueryOptions): Observable ({ - fromCache: memo.type === 'memo', - documents: memo.value, - })), - ) - : map((documents) => ({ - fromCache: false, - documents, - })), + swr(swrKey), + map(({fromCache, value}) => ({fromCache, documents: value})), ) } - -const lru = new QuickLRU({maxSize: 100}) -function memoLRU( - memoKey: string, - cache: QuickLRU, -): OperatorFunction { - return (input$: Observable) => - 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, - })), - ), - ) -}