fix(node-ws): use defineWebSocket helper (#1187)

* fix: use buffering to fix #1129

* chore: changeset

* chore: fmt

* feat(node-ws): use defineWebSocket helper

* changeset
pull/1189/head
Shotaro Nakamura 2025-06-02 21:06:25 +09:00 committed by GitHub
parent 3c70dcd6ae
commit 69a0a586f5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 92 additions and 112 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/node-ws': patch
---
use defineWebSocket helper

View File

@ -0,0 +1,5 @@
---
'@hono/node-ws': patch
---
fix a bug if upgrading process uses async function

View File

@ -215,26 +215,6 @@ describe('WebSocket helper', () => {
})
})
it('Should onError works well', async () => {
const mainPromise = new Promise<unknown>((resolve) =>
app.get(
'/',
upgradeWebSocket(
() => {
throw 0
},
{
onError(err) {
resolve(err)
},
}
)
)
)
const ws = new WebSocket('ws://localhost:3030/')
expect(await mainPromise).toBe(0)
})
describe('Types', () => {
it('Should not throw a type error with an app with Variables generics', () => {
const app = new Hono<{

View File

@ -1,4 +1,5 @@
import type { Hono } from 'hono'
import { defineWebSocketHelper } from 'hono/ws'
import type { UpgradeWebSocket, WSContext, WSEvents } from 'hono/ws'
import type { WebSocket } from 'ws'
import { WebSocketServer } from 'ws'
@ -94,11 +95,9 @@ export const createNodeWebSocket = (init: NodeWebSocketInit): NodeWebSocket => {
})
})
},
upgradeWebSocket: (createEvents, options) =>
async function upgradeWebSocket(c, next) {
upgradeWebSocket: defineWebSocketHelper(async (c, events, options) => {
if (c.req.header('upgrade')?.toLowerCase() !== 'websocket') {
// Not websocket
await next()
return
}
@ -114,15 +113,6 @@ export const createNodeWebSocket = (init: NodeWebSocketInit): NodeWebSocket => {
}
ws.on('message', bufferMessage)
let events: WSEvents<WebSocket>
try {
events = await createEvents(c)
} catch (e) {
;(options?.onError ?? console.error)(e)
ws.close()
return
}
const ctx: WSContext<WebSocket> = {
binaryType: 'arraybuffer',
close(code, reason) {
@ -195,6 +185,6 @@ export const createNodeWebSocket = (init: NodeWebSocketInit): NodeWebSocket => {
})()
return new Response()
},
}),
}
}