Skip to content

Commit

Permalink
feat: support relative paths when generating rest handlers (#267)
Browse files Browse the repository at this point in the history
  • Loading branch information
timkolotov committed Mar 5, 2023
1 parent 5be9ca3 commit 0695b58
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
5 changes: 3 additions & 2 deletions src/model/generateRestHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ type RequestParams<Key extends PrimaryKeyType> = {

export function createUrlBuilder(baseUrl?: string) {
return (path: string) => {
const url = new URL(path, baseUrl || 'http://localhost')
return baseUrl ? url.toString() : url.pathname
// For the previous implementation trailing slash didn't matter, we must keep it this way for backward compatibility
const normalizedBaseUrl = baseUrl && baseUrl.slice(-1) === '/' ? baseUrl.slice(0, -1) : baseUrl || '';
return `${normalizedBaseUrl}/${path}`
}
}

Expand Down
16 changes: 13 additions & 3 deletions test/utils/generateRestHandlers.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { response, restContext } from 'msw'
import { primaryKey } from '../..'
import { primaryKey } from '../../src'
import { ModelDefinition } from '../../src/glossary'
import {
OperationError,
Expand All @@ -15,12 +15,22 @@ import {
describe('createUrlBuilder', () => {
it('builds a relative URL given no base URL', () => {
const buildUrl = createUrlBuilder()
expect(buildUrl('/users')).toEqual('/users')
expect(buildUrl('users')).toEqual('/users')
})

it('builds a relative URL given a prefix as a base URL', () => {
const buildUrl = createUrlBuilder('/api/v1')
expect(buildUrl('users')).toEqual('/api/v1/users')
})

it('builds an absolute URL given a base URL', () => {
const buildUrl = createUrlBuilder('https://example.com')
expect(buildUrl('/users')).toEqual('https://example.com/users')
expect(buildUrl('users')).toEqual('https://example.com/users')
})

it('builds an absolute URL given a base URL with trailing slash', () => {
const buildUrl = createUrlBuilder('https://example.com/')
expect(buildUrl('users')).toEqual('https://example.com/users')
})
})

Expand Down

0 comments on commit 0695b58

Please sign in to comment.