-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathhandler.ts
More file actions
37 lines (34 loc) · 948 Bytes
/
handler.ts
File metadata and controls
37 lines (34 loc) · 948 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Handler for Service Worker
* @module
*/
import type { Hono } from '../../hono'
import type { Env, Schema } from '../../types'
import type { FetchEvent } from './types'
type Handler = (evt: FetchEvent) => void
export type HandleOptions = {
fetch?: typeof fetch
}
/**
* Adapter for Service Worker
*/
export const handle = <E extends Env, S extends Schema, BasePath extends string>(
app: Hono<E, S, BasePath>,
opts: HandleOptions = {
// To use `fetch` on a Service Worker correctly, bind it to `globalThis`.
fetch: globalThis.fetch.bind(globalThis),
}
): Handler => {
return (evt) => {
evt.respondWith(
(async () => {
// @ts-expect-error Passing FetchEvent but app.fetch expects ExecutionContext
const res = await app.fetch(evt.request, {}, evt)
if (opts.fetch && res.status === 404) {
return await opts.fetch(evt.request)
}
return res
})()
)
}
}