feat: implement asset fetching and routing for docs in worker and add server hooks
This commit is contained in:
@@ -14,8 +14,26 @@ const requestHandler = createRequestHandler(
|
||||
import.meta.env.MODE
|
||||
);
|
||||
|
||||
const BASENAME = '/docs';
|
||||
|
||||
export default {
|
||||
fetch(request, env, ctx) {
|
||||
async fetch(request, env, ctx) {
|
||||
const url = new URL(request.url);
|
||||
|
||||
// The app is built with base: '/docs', so HTML references assets at
|
||||
// /docs/assets/... and /docs/*.webp, but the ASSETS binding only knows
|
||||
// about the flat build/client/ layout. Re-fetch with the prefix stripped
|
||||
// so static files resolve before we fall through to SSR.
|
||||
if (url.pathname.startsWith(`${BASENAME}/`)) {
|
||||
const strippedUrl = new URL(url);
|
||||
strippedUrl.pathname = url.pathname.slice(BASENAME.length);
|
||||
|
||||
const assetResponse = await env.ASSETS.fetch(new Request(strippedUrl, request));
|
||||
if (assetResponse.status !== 404) {
|
||||
return assetResponse;
|
||||
}
|
||||
}
|
||||
|
||||
return requestHandler(request, {
|
||||
cloudflare: { env, ctx }
|
||||
});
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Handle } from '@sveltejs/kit';
|
||||
|
||||
const DOCS_ORIGIN = 'https://cio-docs.digdippa.workers.dev';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
const { pathname } = event.url;
|
||||
|
||||
if (pathname === '/docs' || pathname.startsWith('/docs/')) {
|
||||
const upstream = new URL(pathname + event.url.search, DOCS_ORIGIN);
|
||||
|
||||
const headers = new Headers(event.request.headers);
|
||||
headers.delete('host');
|
||||
headers.set('x-forwarded-host', event.url.host);
|
||||
headers.set('x-forwarded-proto', 'https');
|
||||
|
||||
const hasBody = event.request.method !== 'GET' && event.request.method !== 'HEAD';
|
||||
|
||||
return fetch(upstream, {
|
||||
method: event.request.method,
|
||||
headers,
|
||||
body: hasBody ? event.request.body : undefined,
|
||||
redirect: 'manual'
|
||||
});
|
||||
}
|
||||
|
||||
return resolve(event);
|
||||
};
|
||||
Reference in New Issue
Block a user