Skip to content

Commit

Permalink
update assets endpoint (#2288)
Browse files Browse the repository at this point in the history
  • Loading branch information
srliao authored Dec 5, 2024
1 parent 7131286 commit 68f0407
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 21 deletions.
39 changes: 18 additions & 21 deletions ui/packages/workers/src/assets/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { IRequest } from "itty-router";
import {IRequest} from 'itty-router';

export async function handleAssets(
request: IRequest,
event: FetchEvent
event: FetchEvent,
): Promise<Response> {
const cacheUrl = new URL(request.url);
const cacheKey = new Request(cacheUrl.toString(), request);
Expand All @@ -12,30 +12,27 @@ export async function handleAssets(

if (!response) {
console.log(
`Response for request url: ${request.url} not present in cache. Fetching and caching request.`
`Response for request url: ${request.url} not present in cache. Fetching and caching request.`,
);

///api/assets/avatar/cyno.png
const key = new URL(request.url).pathname.replace("/api/assets/", "");
console.log(`getting ${key}`);
const x = new URL(request.url);
const resp = await fetch(
new Request(ASSETS_ENDPOINT + x.pathname + x.search),
{
cf: {
cacheTtl: 60 * 24 * 60 * 60,
cacheEverything: true,
},
},
);

const object = await GCSIM_ASSETS.get(key);
response = new Response(resp.body, resp);
response.headers.set('Cache-Control', 'max-age=5184000');

if (object === null) {
console.log(`${key} not found in r2`);
return new Response(`Not Found`, { status: 404 });
// only cache if response = 200
if (resp.status === 200) {
event.waitUntil(cache.put(cacheKey, response.clone()));
}

const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set("etag", object.httpEtag);
headers.set("Cache-Control", "max-age=5184000");

response = new Response(object.body, {
headers,
});

event.waitUntil(cache.put(cacheKey, response.clone()));
}

return response;
Expand Down
1 change: 1 addition & 0 deletions ui/packages/workers/src/bindings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export {};
declare global {
const API_ENDPOINT: string;
const PREVIEW_ENDPOINT: string;
const ASSETS_ENDPOINT: string;
const GCSIM_ASSETS: R2Bucket; //bucket
const GCSIM_WASM: R2Bucket; //bucket
}

0 comments on commit 68f0407

Please sign in to comment.