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

fix(service-worker): bind fetch to globalThis #3500

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
37 changes: 37 additions & 0 deletions src/adapter/service-worker/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,30 @@ import { Hono } from '../../hono'
import { handle } from './handler'
import type { FetchEvent } from './types'

beforeAll(() => {
// fetch errors when it's not bound to globalThis in service worker
// set a fetch stub to emulate that behavior
vi.stubGlobal(
'fetch',
function fetch(this: undefined | typeof globalThis, arg0: string | Request) {
if (this !== globalThis) {
const error = new Error(
'Failed to execute \'fetch\' on \'WorkerGlobalScope\': Illegal invocation'
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
)
error.name = 'TypeError'
throw error
}
if (arg0 instanceof Request && arg0.url === 'http://localhost/fallback') {
return new Response('hello world')
}
return Response.error()
}
)
})
afterAll(() => {
vi.unstubAllGlobals()
})

describe('handle', () => {
it('Success to fetch', async () => {
const app = new Hono()
Expand All @@ -20,6 +44,19 @@ describe('handle', () => {
expect(json).toStrictEqual({ hello: 'world' })
})
it('Fallback 404', async () => {
const app = new Hono()
const handler = handle(app)
const text = await new Promise<Response>((resolve) => {
handler({
request: new Request('http://localhost/fallback'),
respondWith(res) {
resolve(res)
},
} as FetchEvent)
}).then((res) => res.text())
expect(text).toBe('hello world')
})
it('Fallback 404 with explicit fetch', async () => {
const app = new Hono()
const handler = handle(app, {
async fetch() {
Expand Down
4 changes: 2 additions & 2 deletions src/adapter/service-worker/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export const handle = (
opts: {
fetch?: typeof fetch
} = {
// To use `fetch` on a Service Worker correctly, first refer to `self.fetch`.
fetch: globalThis.self !== undefined ? globalThis.self.fetch : fetch,
// To use `fetch` on a Service Worker correctly, bind it to `globalThis`.
fetch: globalThis.fetch.bind(globalThis),
}
): Handler => {
return (evt) => {
Expand Down
Loading