File size: 753 Bytes
6b3405c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { PreviewServer, ViteDevServer } from "vite";
import { match, Pattern } from "ts-pattern";

export function cacheServerHook<T extends ViteDevServer | PreviewServer>(
  server: T,
) {
  server.middlewares.use(async (request, response, next) => {
    const cacheControlValue = match(request.url)
      .with(
        Pattern.string.startsWith("/assets/"),
        () => "public, max-age=31536000, immutable",
      )
      .with(
        Pattern.union(
          "/",
          Pattern.string.startsWith("/?"),
          Pattern.string.endsWith(".html"),
        ),
        () => "no-cache",
      )
      .otherwise(() => "public, max-age=86400, must-revalidate");

    response.setHeader("Cache-Control", cacheControlValue);

    next();
  });
}