openapi-typescript icon indicating copy to clipboard operation
openapi-typescript copied to clipboard

[openapi-fetch] Provide `client.request()` to support dynamic method.

Open kerwanp opened this issue 6 months ago • 1 comments

Description

Currently, openapi-fetch uses the method as the function name (ex: client.GET()) and there is no way to use the method as an argument. When building around openapi-fetch it requires a bit of gymnastic and manual typing to have a dynamic method.

          const mth = method.toUpperCase() as keyof typeof client;
          const fn = client[mth] as ClientMethod<Paths, typeof method, Media>;

We can also find this pattern in libraries like axios, ky, etc.

Proposal

Internally, openapi-fetch already use coreFetch method to pass the method as an argument.

We could have a request (or REQUEST to respect casing) method on the client. (or FETCH).

  return {
    /** Call an endpoint */
    async REQUEST(method, url, init) {
          return coreFetch(url, { ...init, method });
    }
    /** Call a GET endpoint */
    async GET(url, init) {
      return coreFetch(url, { ...init, method: "GET" });
    },
    /** Call a PUT endpoint */
    async PUT(url, init) {
      return coreFetch(url, { ...init, method: "PUT" });
    },
    /** Call a POST endpoint */
    async POST(url, init) {
      return coreFetch(url, { ...init, method: "POST" });
    },
    [...]
  }

Checklist

kerwanp avatar Aug 02 '24 11:08 kerwanp