From 2134b275609decc3048f03e6cc17f3e40047b2af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rge=20N=C3=A6ss?= Date: Thu, 22 Dec 2022 17:30:36 +0100 Subject: [PATCH] fix(base): wait for all chunked requests to arrive before continuing (#4017) Our previous approach of chunking document availability requests did not wait for all the chunks to finish before returning the results. The debounceCollect utility expects an observable that returns all results in one go, but because we returned a stream that would emit the chunks one-by-one as they arrived, we would only handle the first emission, which would not include the whole result set, breaking assumptions further down the line. This patch fixes the issue by reducing over each emission, successively add them to an array. (the reduce operator will wait for the stream to finish before emitting a single reduced value). --- packages/sanity/src/core/preview/availability.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/sanity/src/core/preview/availability.ts b/packages/sanity/src/core/preview/availability.ts index c7898aa113d..afb9f21eecf 100644 --- a/packages/sanity/src/core/preview/availability.ts +++ b/packages/sanity/src/core/preview/availability.ts @@ -2,7 +2,7 @@ import type {SanityClient} from '@sanity/client' import {combineLatest, defer, from, Observable, of} from 'rxjs' -import {distinctUntilChanged, map, mergeMap, switchMap} from 'rxjs/operators' +import {distinctUntilChanged, map, mergeMap, reduce, switchMap} from 'rxjs/operators' import shallowEquals from 'shallow-equals' import {flatten, keyBy} from 'lodash' import {getDraftId, getPublishedId, isRecord} from '../util' @@ -56,6 +56,16 @@ function chunkDocumentIds(documentIds: string[]): string[][] { return chunks } +/** + * Mutative concat + * @param array - the array to concat to + * @param chunks - the items to concat to the array + */ +function mutConcat(array: T[], chunks: T[]) { + array.push(...chunks) + return array +} + export function create_preview_availability( versionedClient: SanityClient, observePaths: ObservePathsFn @@ -111,6 +121,7 @@ export function create_preview_availability( const uniqueIds = [...new Set(flatten(args))] return from(chunkDocumentIds(uniqueIds)).pipe( mergeMap(fetchDocumentReadabilityChunked, 10), + reduce(mutConcat, []), map((res) => args.map(([id]) => res[uniqueIds.indexOf(id)])) ) },