diff --git a/.changeset/heavy-onions-bake.md b/.changeset/heavy-onions-bake.md new file mode 100644 index 000000000..b6a7c4f4d --- /dev/null +++ b/.changeset/heavy-onions-bake.md @@ -0,0 +1,5 @@ +--- +"openapi-fetch": patch +--- + +fix dynamic access to methods using wrapAsPathBasedClient diff --git a/packages/openapi-fetch/src/index.js b/packages/openapi-fetch/src/index.js index ad83112e0..171187254 100644 --- a/packages/openapi-fetch/src/index.js +++ b/packages/openapi-fetch/src/index.js @@ -298,30 +298,30 @@ class PathCallForwarder { this.url = url; } - GET(init) { + GET = (init) => { return this.client.GET(this.url, init); - } - PUT(init) { + }; + PUT = (init) => { return this.client.PUT(this.url, init); - } - POST(init) { + }; + POST = (init) => { return this.client.POST(this.url, init); - } - DELETE(init) { + }; + DELETE = (init) => { return this.client.DELETE(this.url, init); - } - OPTIONS(init) { + }; + OPTIONS = (init) => { return this.client.OPTIONS(this.url, init); - } - HEAD(init) { + }; + HEAD = (init) => { return this.client.HEAD(this.url, init); - } - PATCH(init) { + }; + PATCH = (init) => { return this.client.PATCH(this.url, init); - } - TRACE(init) { + }; + TRACE = (init) => { return this.client.TRACE(this.url, init); - } + }; } class PathClientProxyHandler { diff --git a/packages/openapi-fetch/test/path-based-client/path-based-client.test.ts b/packages/openapi-fetch/test/path-based-client/path-based-client.test.ts index 25148b300..810e87179 100644 --- a/packages/openapi-fetch/test/path-based-client/path-based-client.test.ts +++ b/packages/openapi-fetch/test/path-based-client/path-based-client.test.ts @@ -1,5 +1,5 @@ import type { MediaType } from "openapi-typescript-helpers"; -import { createExpect, describe, expect, expectTypeOf, test } from "vitest"; +import { describe, expect, expectTypeOf, test } from "vitest"; import { createPathBasedClient, type PathBasedClient } from "../../src/index.js"; import type { paths } from "./schemas/path-based-client.js"; @@ -78,5 +78,21 @@ describe("createPathBasedClient", () => { expect(data.title).toBe("Blog post title"); } }); + + test('properly binds "this" inside PathCallForwarder', async () => { + let method = ""; + const client = createObservedPathBasedClient({}, async (req) => { + method = req.method; + return Response.json({}); + }); + + const getMethodByPathAndMethod = (path: "/posts", method: "GET") => { + return client[path][method]; + }; + + await getMethodByPathAndMethod("/posts", "GET")(); + + expect(method).toBe("GET"); + }); }); });