Skip to content

Commit

Permalink
refactor(cloudflare-module): extract reusable logic (#2799)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Oct 18, 2024
1 parent b9fcc83 commit 749f455
Show file tree
Hide file tree
Showing 2 changed files with 126 additions and 101 deletions.
123 changes: 123 additions & 0 deletions src/presets/cloudflare/runtime/_module-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import "#nitro-internal-pollyfills";
import type * as CF from "@cloudflare/workers-types";
import type { ExportedHandler } from "@cloudflare/workers-types";
import { useNitroApp } from "nitropack/runtime";
import { requestHasBody, runCronTasks } from "nitropack/runtime/internal";

type MaybePromise<T> = T | Promise<T>;

export function createHandler<Env>(hooks: {
fetch: (
...params: Parameters<NonNullable<ExportedHandler<Env>["fetch"]>>
) => MaybePromise<Response | CF.Response | undefined>;
}) {
const nitroApp = useNitroApp();

return <ExportedHandler<Env>>{
async fetch(request, env, context) {
// Preset-specific logic
if (hooks.fetch) {
const res = await hooks.fetch(request, env, context);
if (res) {
return res;
}
}

const url = new URL(request.url);
let body;
if (requestHasBody(request as unknown as Request)) {
body = Buffer.from(await request.arrayBuffer());
}

// Expose latest env to the global context
(globalThis as any).__env__ = env;

return nitroApp.localFetch(url.pathname + url.search, {
context: {
cf: (request as any).cf,
waitUntil: (promise: Promise<any>) => context.waitUntil(promise),
cloudflare: {
request,
env,
context,
},
},
host: url.hostname,
protocol: url.protocol,
method: request.method,
headers: request.headers as unknown as Headers,
body,
}) as unknown as Promise<Response>;
},

scheduled(controller, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:scheduled", {
controller,
env,
context,
})
);
if (import.meta._tasks) {
context.waitUntil(
runCronTasks(controller.cron, {
context: {
cloudflare: {
env,
context,
},
},
payload: {},
})
);
}
},

email(message, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:email", {
message,
event: message, // backward compat
env,
context,
})
);
},

queue(batch, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:queue", {
batch,
event: batch,
env,
context,
})
);
},

tail(traces, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:tail", {
traces,
env,
context,
})
);
},

trace(traces, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:trace", {
traces,
env,
context,
})
);
},
};
}
104 changes: 3 additions & 101 deletions src/presets/cloudflare/runtime/cloudflare-module.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import "#nitro-internal-pollyfills";
import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
import { requestHasBody, runCronTasks } from "nitropack/runtime/internal";
import { getPublicAssetMeta } from "#nitro-internal-virtual/public-assets";

import {
getAssetFromKV,
mapRequestToAsset,
} from "@cloudflare/kv-asset-handler";
import type { ExportedHandler } from "@cloudflare/workers-types";
import wsAdapter from "crossws/adapters/cloudflare";
import { withoutBase } from "ufo";
import { createHandler } from "./_module-handler";

// @ts-ignore Bundled by Wrangler
// See https://github.com/cloudflare/kv-asset-handler#asset_manifest-required-for-es-modules
Expand All @@ -25,7 +23,7 @@ interface Env {
__STATIC_CONTENT?: any;
}

export default <ExportedHandler<Env>>{
export default createHandler<Env>({
async fetch(request, env, context) {
// Websocket upgrade
// https://crossws.unjs.io/adapters/cloudflare
Expand Down Expand Up @@ -55,104 +53,8 @@ export default <ExportedHandler<Env>>{
} catch {
// Ignore
}

const url = new URL(request.url);
let body;
if (requestHasBody(request as unknown as Request)) {
body = Buffer.from(await request.arrayBuffer());
}

// Expose latest env to the global context
(globalThis as any).__env__ = env;

return nitroApp.localFetch(url.pathname + url.search, {
context: {
cf: (request as any).cf,
waitUntil: (promise: Promise<any>) => context.waitUntil(promise),
cloudflare: {
request,
env,
context,
},
},
host: url.hostname,
protocol: url.protocol,
method: request.method,
headers: request.headers as unknown as Headers,
body,
});
},

scheduled(controller, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:scheduled", {
controller,
env,
context,
})
);
if (import.meta._tasks) {
context.waitUntil(
runCronTasks(controller.cron, {
context: {
cloudflare: {
env,
context,
},
},
payload: {},
})
);
}
},

email(message, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:email", {
message,
event: message, // backward compat
env,
context,
})
);
},

queue(batch, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:queue", {
batch,
event: batch,
env,
context,
})
);
},

tail(traces, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:tail", {
traces,
env,
context,
})
);
},

trace(traces, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:trace", {
traces,
env,
context,
})
);
},
};
});

function assetsCacheControl(_request: Request) {
const url = new URL(_request.url);
Expand Down

0 comments on commit 749f455

Please sign in to comment.