From d46b42164008adf024b0666011e260ffb4828ca2 Mon Sep 17 00:00:00 2001 From: lifegpc Date: Thu, 22 Jun 2023 07:26:36 +0800 Subject: [PATCH] Fix 404 not found if sw.js is not exists when server started --- routes/_middleware.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/routes/_middleware.ts b/routes/_middleware.ts index ce5f60e..03e2133 100644 --- a/routes/_middleware.ts +++ b/routes/_middleware.ts @@ -2,6 +2,12 @@ import { MiddlewareHandlerContext } from "$fresh/server.ts"; import { build } from "esbuild/mod.js"; import { join, resolve } from "std/path/mod.ts"; import { asyncForEach, calFileMd5, checkMapFile } from "../utils.ts"; +import { + get_file_response, + GetFileResponseOptions, +} from "../server/get_file_response.ts"; + +const STATIC_FILES = ["/sw.js", "/sw.js.map"]; export async function handler(req: Request, ctx: MiddlewareHandlerContext) { const url = new URL(req.url); @@ -50,9 +56,14 @@ export async function handler(req: Request, ctx: MiddlewareHandlerContext) { console.log("Rebuild."); } } - const res = await ctx.next(); - if (url.pathname == "/sw.js") { - res.headers.delete("etag"); + if (STATIC_FILES.includes(url.pathname)) { + const base = import.meta.resolve("../static").slice(8); + const file = join(base, url.pathname.slice(1)); + const opts: GetFileResponseOptions = {}; + opts.range = req.headers.get("Range"); + opts.if_modified_since = req.headers.get("If-Modified-Since"); + return get_file_response(file, opts); } + const res = await ctx.next(); return res; }