Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(cloudflare-module): extract reusable logic #2799

Merged
merged 1 commit into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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