Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(openapi-fetch): fix overriding baseUrl per request without overriding default baseUrl #2157

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 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,10 @@ 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,
);
let response;

/** Add custom parameters to Request object */
Expand All @@ -109,7 +113,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