Skip to content
Myr

handler.ts

This file

Path

adapters/service-worker/src/handler.ts

37 lines · 941 bytes · TypeScript

Last changed by

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

History of this file

Take it

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 1–37why, one step back
1/**
2 * Handler for Service Worker3 * @module4 */56import type { Hono } from 'hono'7import type { Env, Schema } from 'hono/types'8import type { FetchEvent } from './types'910type Handler = (evt: FetchEvent) => void11export type HandleOptions = {12 fetch?: typeof fetch13}1415/**16 * Adapter for Service Worker17 */18export const handle = <E extends Env, S extends Schema, BasePath extends string>(19 app: Hono<E, S, BasePath>,20 opts: HandleOptions = {21 // To use `fetch` on a Service Worker correctly, bind it to `globalThis`.22 fetch: globalThis.fetch.bind(globalThis),23 }24): Handler => {25 return (evt) => {26 evt.respondWith(27 (async () => {28 // @ts-expect-error Passing FetchEvent but app.fetch expects ExecutionContext29 const res = await app.fetch(evt.request, {}, evt)30 if (opts.fetch && res.status === 404) {31 return await opts.fetch(evt.request)32 }33 return res34 })()35 )36 }37}