Skip to content

Commit

Permalink
fix(cloudflare): fetch publicAssets from KV only
Browse files Browse the repository at this point in the history
  • Loading branch information
oleghalin authored and Hebilicious committed Jul 2, 2023
1 parent d3d0824 commit 003f85c
Showing 1 changed file with 10 additions and 16 deletions.
26 changes: 10 additions & 16 deletions src/runtime/entries/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import {
getAssetFromKV,
mapRequestToAsset,
} from "@cloudflare/kv-asset-handler";
import { parseURL, withLeadingSlash, withoutBase, withoutTrailingSlash } from "ufo";
import { withLeadingSlash, withoutBase, withoutTrailingSlash } from "ufo";
import { splitCookiesString } from "set-cookie-parser";
import { createError } from "h3";
import { requestHasBody } from "../utils";
import { nitroApp } from "#internal/nitro/app";
import { useRuntimeConfig } from "#internal/nitro";
Expand All @@ -16,17 +15,22 @@ addEventListener("fetch", (event: any) => {
});

async function handleEvent(event: FetchEvent) {
try {
const url = new URL(event.request.url);
const id = decodeURIComponent(
withLeadingSlash(
withoutTrailingSlash(url.pathname)
)
);

// Fetch public assets from KV only
if (isPublicAssetURL(id)) {
return await getAssetFromKV(event, {
cacheControl: assetsCacheControl,
mapRequestToAsset: baseURLModifier,
});
} catch {
// Ignore
}


const url = new URL(event.request.url);
let body;
if (requestHasBody(event.request)) {
body = Buffer.from(await event.request.arrayBuffer());
Expand All @@ -49,16 +53,6 @@ async function handleEvent(event: FetchEvent) {

const headers = normalizeOutgoingHeaders(r.headers);

const id = decodeURIComponent(
withLeadingSlash(
withoutTrailingSlash(url.pathname)
)
);

if (r.status === 404 && isPublicAssetURL(id)) {
headers.delete('cache-control')
}

return new Response(r.body, {
// @ts-ignore TODO: Should be HeadersInit instead of string[][]
headers,
Expand Down

0 comments on commit 003f85c

Please sign in to comment.