diff --git a/docs/2.utils/9.more.md b/docs/2.utils/9.more.md index 925922ca6..8e22cf648 100644 --- a/docs/2.utils/9.more.md +++ b/docs/2.utils/9.more.md @@ -81,7 +81,7 @@ You can return a new Response from the handler to replace the original response. Define WebSocket hooks. -### `defineWebSocketHandler(hooks)` +### `defineWebSocketHandler()` Define WebSocket event handler. diff --git a/src/utils/ws.ts b/src/utils/ws.ts index e50e809fa..cd87cc954 100644 --- a/src/utils/ws.ts +++ b/src/utils/ws.ts @@ -1,12 +1,13 @@ import { defineHandler } from "../handler.ts"; import type { Hooks as WebSocketHooks } from "crossws"; +import type { H3Event } from "../event.ts"; import type { EventHandler } from "../types/handler.ts"; export type { Hooks as WebSocketHooks, - Peer as WebSocketPeer, Message as WebSocketMessage, + Peer as WebSocketPeer, } from "crossws"; /** @@ -26,15 +27,21 @@ export function defineWebSocket( * @see https://h3.dev/guide/websocket */ export function defineWebSocketHandler( - hooks: Partial, + hooks: + | Partial + | (( + event: H3Event, + ) => Partial | Promise>), ): EventHandler { - return defineHandler(function _webSocketHandler() { + return defineHandler(function _webSocketHandler(event) { + const crossws = typeof hooks === "function" ? hooks(event) : hooks; + return Object.assign( new Response("WebSocket upgrade is required.", { status: 426, }), { - crossws: hooks, + crossws, }, ); }); diff --git a/test/ws.test.ts b/test/ws.test.ts index 87136bf63..3c666d1f4 100644 --- a/test/ws.test.ts +++ b/test/ws.test.ts @@ -19,4 +19,13 @@ describe("defineWebSocketHandler", () => { // expect((res as Response).statusText).toBe("Upgrade Required"); expect((res as any).crossws).toEqual(hooks); }); + + it("should attach the provided hooks with function argument", () => { + const wsHandler = defineWebSocketHandler(() => hooks); + const res = wsHandler({} as any); + expect(res).toBeInstanceOf(Response); + expect((res as Response).status).toBe(426); + // expect((res as Response).statusText).toBe("Upgrade Required"); + expect((res as any).crossws).toEqual(hooks); + }); });