Support caching for streamed responses

未關閉
#7 3 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
5/5
預估耗時
一週以上
新手友好度
30/100
Issue 類型
缺陷
描述清晰度
需要釐清
活躍度
停滯
技術堆疊
react, typescript

研究方向

從 src/index.tsx 第 116-140 行開始,並重現連結的 StackBlitz/routes/index.tsx 範例中的 fulfilled-promise path。追蹤 deferredServerData、serverData、freshData 和 adapter 的比較方式;完成意味著快取能區分 Promise 已 fulfilled 的快取資料與需要重新驗證的資料,且行為已獲得驗證。

由索引模型根據 Issue 內容生成。

描述

Stackblitz

When using defer to stream a response from a loader that returned a promise which later used in a boundary, we cannot properly serialize the promise to store say in localStorage or IndexedDB (JSON.stringify will result in an empty object {}). The only way to store this type of data is directly in memory, so on the next navigation, clientLoader will return fulfilled promise with the data, rather than calling the server `loader'.

let cache: SerializeFrom<typeof loader>;
export const clientLoader = defineClientLoader(async ({ serverLoader }) => {
    if (!cache) {
        cache = await serverLoader<typeof loader>();
    }

    return cache;
});

clientLoader.hydrate = true;

By using remix-client-cache, we can create an adapter for when we need to cache streaming responses, rather than relying on a global setting using, for example, localStorage.

import { lru } from 'tiny-lru';
import { type CacheAdapter, createCacheAdapter } from 'remix-client-cache';

const cache = lru(100);

class LRUAdapter implements CacheAdapter {
	async getItem(key: string) {
		return cache.get(key);
	}

	async setItem(key: string, value: any) {
		return cache.set(key, value);
	}

	async removeItem(key: string) {
		return cache.delete(key);
	}
}

export const { adapter: lruAdapter } = createCacheAdapter(() => new LRUAdapter());

routes/index.tsx:

import { defer } from '@remix-run/node';
import { Await, ClientLoaderFunctionArgs, Link } from '@remix-run/react';
import { Suspense } from 'react';
import { cacheClientLoader, useCachedLoaderData } from 'remix-client-cache';
import { lruAdapter } from '~/client-cache-adapter';

async function getQueryData() {
	await new Promise((resolve) => setTimeout(resolve, 3000));
	return { data: [{ id: 1 }] };
}

export async function loader() {
	const query = getQueryData();

	return defer({
		query,
	});
}

export const clientLoader = (args: ClientLoaderFunctionArgs) => cacheClientLoader(args, { adapter: lruAdapter });
clientLoader.hydrate = true;

export default function Page() {
	const { query } = useCachedLoaderData<typeof loader>();

	return (
		<>
			<Link to="/">Home</Link>

			<br />
			<br />

			<Suspense fallback="loading...">
				<Await resolve={query}>
					{({ data }) => (
						<ul>
							{data?.map((entry) => <li key={entry.id}>{entry.id}</li>)}
						</ul>
					)}
				</Await>
			</Suspense>
		</>
	);
}

This opens up a question whether it's a good idea to store data in server memory, it would be interesting if we could transform fulfilled promises using a library like turbo-stream to store on the client-side or use a web worker and decode to the original form for consumption by .


There is currently a bug where a returned promise from the cache has already been fulfilled, the internal logic of remix-client-cache cannot understand when a revalidation should occur, or fulfilled data is currently present, since we must store promises directly in memory and not as a string.
https://github.com/forge42dev/remix-client-cache/blob/main/src/index.tsx#L116-L140

// Unpack deferred data from the server
useEffect(() => {
	let isMounted = true;
	if (loaderData.deferredServerData) {
		loaderData.deferredServerData.then((newData: any) => {
			if (isMounted) {
				adapter.setItem(loaderData.key, newData);
				setFreshData(newData);
			}
		});
	}
	return () => {
		isMounted = false;
	};
}, [loaderData, adapter]);

// Update the cache if the data changes
useEffect(() => {
	if (
		loaderData.serverData &&
		JSON.stringify(loaderData.serverData) !== JSON.stringify(freshData)
	) {
		setFreshData(loaderData.serverData);
	}
}, [loaderData?.serverData, freshData]);
主要語言
TypeScript
星號
247
分支
3
PR 合併指標
30 天內沒有已合併 PR

環境準備

  • 沒有 Dockerfile 或 Docker Compose 檔案
  • 有 Pull Request 範本
  • 沒有貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

code-forge-io/remix-client-cache 的其他 Issue

查看 code-forge-io/remix-client-cache 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。