Skip to content

Commit

Permalink
fix(client): replace optional params to url correctly (#3304)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored Aug 21, 2024
1 parent 95a6b39 commit 331b3d8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
15 changes: 14 additions & 1 deletion src/client/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -815,7 +815,9 @@ describe('Infer the response type with different status codes', () => {
})

describe('$url() with a param option', () => {
const app = new Hono().get('/posts/:id/comments', (c) => c.json({ ok: true }))
const app = new Hono()
.get('/posts/:id/comments', (c) => c.json({ ok: true }))
.get('/something/:firstId/:secondId/:version?', (c) => c.json({ ok: true }))
type AppType = typeof app
const client = hc<AppType>('http://localhost')

Expand All @@ -832,6 +834,17 @@ describe('$url() with a param option', () => {
const url = client.posts[':id'].comments.$url()
expect(url.pathname).toBe('/posts/:id/comments')
})

it('Should return the correct path - /something/123/456', async () => {
const url = client.something[':firstId'][':secondId'][':version?'].$url({
param: {
firstId: '123',
secondId: '456',
version: undefined,
},
})
expect(url.pathname).toBe('/something/123/456')
})
})

describe('Client can be awaited', () => {
Expand Down
11 changes: 11 additions & 0 deletions src/client/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ describe('replaceUrlParams', () => {
const replacedUrl = replaceUrlParam(url, params)
expect(replacedUrl).toBe('http://localhost/year/2024/month/2')
})

it('Should replace correctly when it has optional parameters', () => {
const url = 'http://localhost/something/:firstId/:secondId/:version?'
const params = {
firstId: '123',
secondId: '456',
version: undefined,
}
const replacedUrl = replaceUrlParam(url, params)
expect(replacedUrl).toBe('http://localhost/something/123/456')
})
})

describe('replaceUrlProtocol', () => {
Expand Down
6 changes: 3 additions & 3 deletions src/client/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ export const mergePath = (base: string, path: string) => {
return base + path
}

export const replaceUrlParam = (urlString: string, params: Record<string, string>) => {
export const replaceUrlParam = (urlString: string, params: Record<string, string | undefined>) => {
for (const [k, v] of Object.entries(params)) {
const reg = new RegExp('/:' + k + '(?:{[^/]+})?')
urlString = urlString.replace(reg, `/${v}`)
const reg = new RegExp('/:' + k + '(?:{[^/]+})?\\??')
urlString = urlString.replace(reg, v ? `/${v}` : '')
}
return urlString
}
Expand Down

0 comments on commit 331b3d8

Please sign in to comment.