Skip to content

Commit

Permalink
fix(openapi-fetch): fix overriding baseUrl per request without overri…
Browse files Browse the repository at this point in the history
…ding default baseUrl
  • Loading branch information
Rendez committed Feb 14, 2025
1 parent 82e98b4 commit 68b880b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/openapi-fetch/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ export default function createClient(clientOptions) {
body,
...init
} = fetchOptions || {};
let finalBaseUrl = baseUrl;
if (localBaseUrl) {
baseUrl = removeTrailingSlash(localBaseUrl);
finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
}

let querySerializer =
Expand Down Expand Up @@ -94,7 +95,7 @@ export default function createClient(clientOptions) {

let id;
let options;
let request = new CustomRequest(createFinalURL(schemaPath, { baseUrl, params, querySerializer }), requestInit);
let request = new CustomRequest(createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer }), requestInit);

/** Add custom parameters to Request object */
for (const key in init) {
Expand All @@ -108,7 +109,7 @@ export default function createClient(clientOptions) {

// middleware (request)
options = Object.freeze({
baseUrl,
baseUrl: finalBaseUrl,
fetch,
parseAs,
querySerializer,
Expand Down
19 changes: 19 additions & 0 deletions packages/openapi-fetch/test/common/create-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,25 @@ describe("createClient options", () => {
expect(actualURL.href).toBe("https://api.foo.bar/v3/resources");
});

test("baseUrl per request causes no override on default baseUrl", async () => {
let actualURL = new URL("https://fakeurl.example");
const client = createObservedClient<paths>({ baseUrl: "https://api.foo.bar/v2/" }, async (req) => {
actualURL = new URL(req.url);
return Response.json([]);
});

const localBaseUrl = "https://api.foo.bar/v3";
await client.GET("/resources", { baseUrl: localBaseUrl });

// assert baseUrl and path mesh as expected
expect(actualURL.href).toBe("https://api.foo.bar/v3/resources");

await client.GET("/resources");

// assert baseUrl and path mesh as expected
expect(actualURL.href).toBe("https://api.foo.bar/v2/resources");
});

describe("content-type", () => {
const BODY_ACCEPTING_METHODS = [["PUT"], ["POST"], ["DELETE"], ["OPTIONS"], ["PATCH"]] as const;
const ALL_METHODS = [...BODY_ACCEPTING_METHODS, ["GET"], ["HEAD"]] as const;
Expand Down

0 comments on commit 68b880b

Please sign in to comment.