mirror of https://github.com/fantasticit/think.git
29 lines
696 B
TypeScript
29 lines
696 B
TypeScript
import { NextPageContext } from 'next';
|
|
import { dehydrate, QueryClient } from 'react-query';
|
|
|
|
type PrefetchActions = Array<{
|
|
url: string;
|
|
action: (cookie: string) => void;
|
|
ignoreCookie?: boolean;
|
|
}>;
|
|
|
|
export async function serverPrefetcher(ctx: NextPageContext, actions: PrefetchActions) {
|
|
const cookie = ctx.req?.headers?.cookie;
|
|
|
|
if (!cookie && !actions.filter((action) => action.ignoreCookie === true).length) {
|
|
return {};
|
|
}
|
|
|
|
const queryClient = new QueryClient();
|
|
|
|
await Promise.all(
|
|
actions.map((action) => {
|
|
return queryClient.prefetchQuery(action.url, () => action.action(cookie));
|
|
})
|
|
);
|
|
|
|
return {
|
|
dehydratedState: dehydrate(queryClient),
|
|
};
|
|
}
|