Privately cache user build tab response to avoid repeated requests

This commit is contained in:
Kalle 2023-08-13 15:36:29 +03:00
parent 37dedb0720
commit fa83790dff
2 changed files with 13 additions and 2 deletions

View File

@ -1,4 +1,3 @@
import { json } from "@remix-run/node";
import type { ActionFunction, LoaderArgs } from "@remix-run/node";
import { useLoaderData, useMatches } from "@remix-run/react";
import { z } from "zod";
@ -13,6 +12,7 @@ import { atOrError } from "~/utils/arrays";
import {
notFoundIfFalsy,
parseRequestFormData,
privatelyCachedJson,
type SendouRouteHandle,
} from "~/utils/remix";
import { userNewBuildPage } from "~/utils/urls";
@ -66,7 +66,7 @@ export const loader = async ({ params, request }: LoaderArgs) => {
throw new Response(null, { status: 404 });
}
return json({
return privatelyCachedJson({
builds,
weaponCounts: calculateWeaponCounts(),
});

View File

@ -2,6 +2,7 @@ import { z } from "zod";
import { type TFunction, type Namespace } from "react-i18next";
import { type RouteMatch } from "@remix-run/react";
import type navItems from "~/components/layout/nav-items.json";
import { json } from "@remix-run/node";
export function notFoundIfFalsy<T>(value: T | null | undefined): T {
if (!value) throw new Response(null, { status: 404 });
@ -150,3 +151,13 @@ export type SendouRouteHandle = {
/** The name of a navItem that is active on this route. See nav-items.json */
navItemName?: (typeof navItems)[number]["name"];
};
/** Caches the loader response with "private" Cache-Control meaning that CDN won't cache the response.
* To be used when the response is different for each user. This is especially useful when the response
* is prefetched on link hover.
*/
export function privatelyCachedJson<T>(data: T) {
return json(data, {
headers: { "Cache-Control": "private, max-age=20" },
});
}