enkot / nuxt-open-fetch

Generate zero-overhead, typed OpenAPI clients for Nuxt.
https://nuxt-open-fetch.vercel.app
MIT License
114 stars 10 forks source link

Root path is not respected #20

Closed AntoninRousset closed 6 months ago

AntoninRousset commented 6 months ago

Description

Provided a baseURL like http://localhost/api or /api, the root path is not respected by useOpenFetch:

useApiFetch("/items/")  // fetches "/items" instead of "/api/items"

This is somehow expected when using useFetch because of the leading slash, but not when referring to an OpenAPI schema

{
  "openapi": "3.1.0",
  "info": {
    "title": "API",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "/api"
    }
  ],
  "paths": {
    "/items/": ...
  }
}

Workaround

You might remove the leading slash, but then typecheck complains. I ended up removing it programmatically inside the UseOpenFetchClient:

diff --git a/src/runtime/clients.ts b/src/runtime/clients.ts
index 0c84a83..785be02 100644
--- a/src/runtime/clients.ts
+++ b/src/runtime/clients.ts
@@ -102,7 +102,7 @@ export function createUseOpenFetch<Paths, Lazy extends boolean = boolean>(client
     const $fetch = (typeof client === 'string' ? nuxtApp[`$${client}Fetch`] : client)
     const opts = { $fetch, key: autoKey, ...options }

-    return useFetch(() => toValue(url), lazy ? { ...opts, lazy } : opts)
+    return useFetch(() => toValue(url).replace(/^\//, ""), lazy ? { ...opts, lazy } : opts)
   }
 }
AntoninRousset commented 6 months ago

My bad, it seems to work fine with v0.4.1