From 0695b582b3afe000f1c82f4d307a0bf0be15dda5 Mon Sep 17 00:00:00 2001 From: Tim Kolotov Date: Sun, 5 Mar 2023 12:40:32 +0200 Subject: [PATCH] feat: support relative paths when generating rest handlers (#267) --- src/model/generateRestHandlers.ts | 5 +++-- test/utils/generateRestHandlers.test.ts | 16 +++++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/model/generateRestHandlers.ts b/src/model/generateRestHandlers.ts index db3043a2..08388653 100644 --- a/src/model/generateRestHandlers.ts +++ b/src/model/generateRestHandlers.ts @@ -31,8 +31,9 @@ type RequestParams = { 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}` } } diff --git a/test/utils/generateRestHandlers.test.ts b/test/utils/generateRestHandlers.test.ts index 2a23b4b4..e14f7ed4 100644 --- a/test/utils/generateRestHandlers.test.ts +++ b/test/utils/generateRestHandlers.test.ts @@ -1,5 +1,5 @@ import { response, restContext } from 'msw' -import { primaryKey } from '../..' +import { primaryKey } from '../../src' import { ModelDefinition } from '../../src/glossary' import { OperationError, @@ -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') }) })