Skip to content

Commit

Permalink
perf: try eagerly initializing proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Mar 8, 2024
1 parent ad306e1 commit 81113d6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 18 deletions.
4 changes: 3 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
{
"extends": ["eslint-config-unjs"],
"rules": {}
"rules": {
"unicorn/prefer-top-level-await": 0,
},
}
29 changes: 12 additions & 17 deletions src/runtime/plugin.dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,20 @@ import type { PlatformProxy } from "wrangler";
// @ts-ignore
import { useRuntimeConfig, getRequestURL } from "#imports";

export default <NitroAppPlugin>function (nitroApp) {
let _proxy: Promise<PlatformProxy>;
const _proxy = _getPlatformProxy()
.catch((error) => {
console.error("Failed to initialize wrangler bindings proxy", error);
return _createStubProxy();
})
.then((proxy) => {
(globalThis as any).__env__ = proxy.env;
return proxy;
});

nitroApp.hooks.hook("request", async (event) => {
// Lazy initialize proxy when first request comes in
if (!_proxy) {
const start = performance.now();
_proxy = _getPlatformProxy()
.catch((error) => {
console.error("Failed to initialize wrangler bindings proxy", error);
return _createStubProxy();
})
.finally(() => {
const time = Math.round(performance.now() - start);
console.info(`✔ Cloudflare dev proxy took ${time}ms to initialize.`);
});
}
(globalThis as any).__env__ = _proxy.then((proxy) => proxy.env);

export default <NitroAppPlugin>function (nitroApp) {
nitroApp.hooks.hook("request", async (event) => {
const proxy = await _proxy;

// Inject the various cf values from the proxy in event and event.context
Expand All @@ -42,7 +38,6 @@ export default <NitroAppPlugin>function (nitroApp) {
// Replicate Nitro production behavior
// https://github.com/unjs/nitro/blob/main/src/runtime/entries/cloudflare-pages.ts#L55
// https://github.com/unjs/nitro/blob/main/src/runtime/app.ts#L120
(globalThis as any).__env__ = proxy.env;
(event.node.req as any).__unenv__ = {
...(event.node.req as any).__unenv__,
waitUntil: event.context.waitUntil,
Expand Down

0 comments on commit 81113d6

Please sign in to comment.