Prefetch weather and RSS feed data during SSR so widgets render with content on first paint instead of showing loading states.
50 lines
1.6 KiB
TypeScript
50 lines
1.6 KiB
TypeScript
import { cache } from "react";
|
|
import type { QueryClient } from "@tanstack/react-query";
|
|
|
|
import { db } from "@homarr/db";
|
|
import { getServerSettingsAsync } from "@homarr/db/queries";
|
|
import type { WidgetKind } from "@homarr/definitions";
|
|
import { createSettings } from "@homarr/settings/creator";
|
|
|
|
import { reduceWidgetOptionsWithDefaultValues } from ".";
|
|
import prefetchForApps from "./app/prefetch";
|
|
import prefetchForBookmarks from "./bookmarks/prefetch";
|
|
import type { Prefetch, WidgetOptionsRecordOf } from "./definition";
|
|
import type { inferOptionsFromCreator } from "./options";
|
|
import prefetchRssFeedsAsync from "./rssFeed/prefetch";
|
|
import prefetchWeatherAsync from "./weather/prefetch";
|
|
|
|
const cachedGetServerSettingsAsync = cache(getServerSettingsAsync);
|
|
|
|
const prefetchCallbacks: Partial<{
|
|
[TKind in WidgetKind]: Prefetch<TKind>;
|
|
}> = {
|
|
bookmarks: prefetchForBookmarks,
|
|
app: prefetchForApps,
|
|
weather: prefetchWeatherAsync,
|
|
rssFeed: prefetchRssFeedsAsync,
|
|
};
|
|
|
|
export const prefetchForKindAsync = async <TKind extends WidgetKind>(
|
|
kind: TKind,
|
|
queryClient: QueryClient,
|
|
items: {
|
|
options: inferOptionsFromCreator<WidgetOptionsRecordOf<TKind>>;
|
|
integrationIds: string[];
|
|
}[],
|
|
) => {
|
|
const callback = prefetchCallbacks[kind];
|
|
if (!callback) {
|
|
return;
|
|
}
|
|
|
|
const serverSettings = await cachedGetServerSettingsAsync(db);
|
|
|
|
const itemsWithDefaultOptions = items.map((item) => ({
|
|
...item,
|
|
options: reduceWidgetOptionsWithDefaultValues(kind, createSettings({ user: null, serverSettings }), item.options),
|
|
}));
|
|
|
|
await callback(queryClient, itemsWithDefaultOptions as never[]);
|
|
};
|