Я начинаю с этого файла, он вызывается с множества страниц и серверных компонентов:
Код: Выделить всё
"use server"
export const getData = async () => {
const data = await fetch("http://foo/getProfileData", {
next:{ revalidate: 60 }
});
return data.json()
}
Поэтому я пробую оболочку кэша React:
Код: Выделить всё
"use server"
import { cache } from "react";
export const getData = cache(async () => {
const data = await fetch("http://foo/getProfileData", {
next:{ revalidate: 60 }
});
return data.json()
})
Поэтому я пытаюсь будьте немного умнее и воспользуйтесь преимуществами кэширования модулей Node:
Код: Выделить всё
import "server-only";
export class ServerCache {
private data: null | T = null;
private expirationMs: number;
private timestamp: null | number = null;
constructor(expirationMs: number) {
this.expirationMs = expirationMs;
}
get(): null | T {
const shouldRevalidate =
!this.data || this.getElapsedMs() > this.expirationMs;
if (shouldRevalidate) {
return null;
}
return this.data;
}
getElapsedMs() {
return this.timestamp ? Date.now() - this.timestamp : Infinity;
}
getRemainingSeconds() {
return (this.expirationMs - this.getElapsedMs()) / 1000;
}
invalidate() {
this.data = null;
this.timestamp = null;
}
set(data: T) {
this.data = data;
this.timestamp = Date.now();
}
}
Код: Выделить всё
"use server"
const cache = new ServerCache(60*1000)
export const getData = async () => {
if (cache.get()) return data;
const data = await fetch("http://foo/getProfileData", {
next:{ revalidate: 60 }
});
const updatedData = await data.json();
cache.set(updatedData)
return updatedData
}
export const revalidate = () => cache.invalidate()
Код: Выделить всё
declare global {
// eslint-disable-next-line no-var
var meCache: ServerCache | undefined;
}
if (!global.meCache) {
console.log("Initializing globalCache module");
global.meCache = new ServerCache(GET.me.revalidate * 1000);
}
export const me = global.meCache;
Это Кажется, это обычный вариант использования отношений между сервером и клиентом, но я не могу понять, как создать кеш между маршрутами, который я могу очистить при необходимости.
Подробнее здесь: https://stackoverflow.com/questions/793 ... -in-nextjs