fix(client): fix websocket client protocol (#2479)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* chore(client): create replaceUrlProtocol * chore(client): fix websocket client url protocol bug * chore(deno_dist): generate deno code * chore(client): add test * chore(client): change test case description * chore(client): add https, wss test
authored by naporitan · committed by GitHub · parent b0d9417 · Browse files · 6 files·+131 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+131 added−7 removed
- tests:+89 added−1 removed
- other:+42 added−6 removed
Provenance
- Commit
1d4c67a- Tree
7580192- Author
naporitan <naporin0624@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
b0d9417
6 files changed+131 added−7 removed
modified:deno_dist/client/client.ts+12 added-3 removed
123456678910111213141516135 unmodified linesExpand all1521531541551501511561571581591601611621631647 unmodified linesimport type { Hono } from '../hono.ts'import type { ValidationTargets } from '../types.ts'import { serialize } from '../utils/cookie.ts'import type { UnionToIntersection } from '../utils/types.ts'import type { Callback, Client, ClientRequestOptions } from './types.ts'import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils.ts'import { deepMerge, mergePath, removeIndexString, replaceUrlParam, replaceUrlProtocol,} from './utils.ts'
const createProxy = (callback: Callback, path: string[]) => { const proxy: unknown = new Proxy(() => {}, { get(_obj, key) {135 unmodified linesExpand all } return new URL(url) } if (method === 'ws') { const targetUrl = opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url const targetUrl = replaceUrlProtocol( opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url, 'ws' )
return new WebSocket(targetUrl) }
const req = new ClientRequestImpl(url, method)7 unmodified linesmodified:deno_dist/client/utils.ts+9 added
13 unmodified lines14 }15 return urlString16 }17 18+export const replaceUrlProtocol = (urlString: string, protocol: 'ws' | 'http') => {19+ switch (protocol) {20+ case 'ws':21+ return urlString.replace(/^http/, 'ws')22+ case 'http':23+ return urlString.replace(/^ws/, 'http')24+ }25+}26+27 export const removeIndexString = (urlSting: string) => {28 return urlSting.replace(/\/index$/, '')29 }30 21 unmodified linesmodified:src/client/client.test.ts+56 added
2 unmodified lines3 /* eslint-disable @typescript-eslint/ban-ts-comment */4 import { rest } from 'msw'5 import { setupServer } from 'msw/node'6 import { expectTypeOf, vi } from 'vitest'7+import { upgradeWebSocket } from '../helper'8 import { Hono } from '../hono'9 import { parse } from '../utils/cookie'10 import type { Equal, Expect } from '../utils/types'11 import { validator } from '../validator'674 unmodified lines686 const data = await res.json()687 expect(data.requestDynamic).toEqual('two')688 })689 })690+691+describe('WebSocket URL Protocol Translation', () => {692+ const app = new Hono()693+ const route = app.get(694+ '/',695+ upgradeWebSocket((c) => ({696+ onMessage(event, ws) {697+ console.log(`Message from client: ${event.data}`)698+ ws.send('Hello from server!')699+ },700+ onClose: () => {701+ console.log('Connection closed')702+ },703+ }))704+ )705+706+ type AppType = typeof route707+708+ const server = setupServer()709+ const webSocketMock = vi.fn()710+711+ beforeAll(() => server.listen())712+ beforeEach(() => {713+ vi.stubGlobal('WebSocket', webSocketMock)714+ })715+ afterEach(() => {716+ vi.clearAllMocks()717+ server.resetHandlers()718+ })719+ afterAll(() => server.close())720+721+ it('Translates HTTP to ws', async () => {722+ const client = hc<AppType>('http://localhost')723+ client.index.$ws()724+ expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/index')725+ })726+727+ it('Translates HTTPS to wss', async () => {728+ const client = hc<AppType>('https://localhost')729+ client.index.$ws()730+ expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/index')731+ })732+733+ it('Keeps ws unchanged', async () => {734+ const client = hc<AppType>('ws://localhost')735+ client.index.$ws()736+ expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/index')737+ })738+739+ it('Keeps wss unchanged', async () => {740+ const client = hc<AppType>('wss://localhost')741+ client.index.$ws()742+ expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/index')743+ })744+})modified:src/client/client.ts+12 added-3 removed
1 unmodified line2 import type { ValidationTargets } from '../types'3 import { serialize } from '../utils/cookie'4 import type { UnionToIntersection } from '../utils/types'5 import type { Callback, Client, ClientRequestOptions } from './types'6-import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils'6+import {7+ deepMerge,8+ mergePath,9+ removeIndexString,10+ replaceUrlParam,11+ replaceUrlProtocol,12+} from './utils'13 14 const createProxy = (callback: Callback, path: string[]) => {15 const proxy: unknown = new Proxy(() => {}, {16 get(_obj, key) {135 unmodified lines152 }153 return new URL(url)154 }155 if (method === 'ws') {150- const targetUrl =151- opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url156+ const targetUrl = replaceUrlProtocol(157+ opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url,158+ 'ws'159+ )160+161 return new WebSocket(targetUrl)162 }163 164 const req = new ClientRequestImpl(url, method)7 unmodified linesmodified:src/client/utils.test.ts+33 added-1 removed
1-import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils'1+import {2+ deepMerge,3+ mergePath,4+ removeIndexString,5+ replaceUrlParam,6+ replaceUrlProtocol,7+} from './utils'8 9 describe('mergePath', () => {10 it('Should merge paths correctly', () => {11 expect(mergePath('http://localhost', '/api')).toBe('http://localhost/api')35 unmodified lines47 expect(replacedUrl).toBe('http://localhost/year/2024/month/2')48 })49 })50 51+describe('replaceUrlProtocol', () => {52+ it('Should replace http to ws', () => {53+ const url = 'http://localhost'54+ const newUrl = replaceUrlProtocol(url, 'ws')55+ expect(newUrl).toBe('ws://localhost')56+ })57+58+ it('Should replace https to wss', () => {59+ const url = 'https://localhost'60+ const newUrl = replaceUrlProtocol(url, 'ws')61+ expect(newUrl).toBe('wss://localhost')62+ })63+64+ it('Should replace ws to http', () => {65+ const url = 'ws://localhost'66+ const newUrl = replaceUrlProtocol(url, 'http')67+ expect(newUrl).toBe('http://localhost')68+ })69+70+ it('Should replace wss to https', () => {71+ const url = 'wss://localhost'72+ const newUrl = replaceUrlProtocol(url, 'http')73+ expect(newUrl).toBe('https://localhost')74+ })75+})76+77 describe('removeIndexString', () => {78 it('Should remove last `/index` string', () => {79 let url = 'http://localhost/index'80 let newUrl = removeIndexString(url)37 unmodified linesmodified:src/client/utils.ts+9 added
13 unmodified lines14 }15 return urlString16 }17 18+export const replaceUrlProtocol = (urlString: string, protocol: 'ws' | 'http') => {19+ switch (protocol) {20+ case 'ws':21+ return urlString.replace(/^http/, 'ws')22+ case 'http':23+ return urlString.replace(/^ws/, 'http')24+ }25+}26+27 export const removeIndexString = (urlSting: string) => {28 return urlSting.replace(/\/index$/, '')29 }30 21 unmodified lines