Skip to content

Commit

Permalink
fix(dev-server) cloudflare adapter restart (#173)
Browse files Browse the repository at this point in the history
Fixes #172

* fix(dev-server): Add null check and error handling for proxy disposal in cloudflareAdapter

* add changeset

* fix: Correct proxy type definition
  • Loading branch information
komapotter authored Aug 30, 2024
1 parent c187bb5 commit 840e6da
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/three-pumas-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/vite-dev-server': patch
---

fix(dev-server): Add null check and error handling for proxy disposal in cloudflareAdapter
24 changes: 15 additions & 9 deletions packages/dev-server/src/adapter/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ type CloudflareAdapterOptions = {
proxy: Parameters<typeof getPlatformProxy>[0]
}

let proxy: Awaited<ReturnType<typeof getPlatformProxy<Env>>>
let proxy: Awaited<ReturnType<typeof getPlatformProxy<Env>>> | undefined = undefined

export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise<Adapter> = async (
options
) => {
proxy ??= await getPlatformProxy(options?.proxy)
// Cache API provided by `getPlatformProxy` currently do nothing.
Object.assign(globalThis, { caches: proxy.caches })

if (typeof globalThis.navigator === 'undefined') {
// @ts-expect-error not typed well
globalThis.navigator = {
Expand All @@ -31,7 +30,10 @@ export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise<

Object.defineProperty(Request.prototype, 'cf', {
get: function () {
return proxy.cf
if (proxy !== undefined) {
return proxy.cf
}
throw new Error('Proxy is not initialized')
},
configurable: true,
enumerable: true,
Expand All @@ -41,12 +43,16 @@ export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise<
env: proxy.env,
executionContext: proxy.ctx,
onServerClose: async () => {
try {
await proxy.dispose()
} catch {
/**
* It throws an error if server is not running.
*/
if (proxy !== undefined) {
try {
await proxy.dispose()
} catch (error) {
/**
* It throws an error if server is not running.
*/
} finally {
proxy = undefined
}
}
},
}
Expand Down

0 comments on commit 840e6da

Please sign in to comment.