johannschopplich / nuxt-api-party

🐬 Securely connect to any API with a server proxy and generated composables
https://nuxt-api-party.byjohann.dev
MIT License
260 stars 10 forks source link

Global headers can be overridden #45

Closed tacxou closed 1 year ago

tacxou commented 1 year ago

Describe the feature

Example ?

export const useApiFetch = <P extends GETPlainPaths<paths>>(
  path: MaybeRefOrGetter<P>,
  opts?: Omit<UseOpenApiDataOptions<paths[`/${P}`], IgnoreCase<keyof paths[`/${P}`] & "get">>, "method"> | undefined,
): AsyncData<P | undefined, FetchError<any>> => {
  return useApiData(path, <any>{
    ...opts,
    onRequest(context): Promise<void> | void {
      context.options.headers = {
        ...context.options.headers,
        'x-api-key': '123', //TODO: get api key from authjs
      }
    }
  })
}

Additional information

Final checks

johannschopplich commented 1 year ago

Indeed, global headers can be overridden by any composable. This is intentional and not a bug, since for a specific request you may want to adapt a certain header, which you have already declared in the apiParty module options. This allows users to have full control without being bound to global defaults in every call.

useApiData(path, {
  headers: {
    // Will overriden the global `foo` header if present
    foo: 'baz'
  }
})
tacxou commented 1 year ago

In fact, I want to act globally. Except that I can't type the composable so that it retains OpenAPI autocompletion. I think an example of this very common authentication case would be necessary.

johannschopplich commented 1 year ago

I see. Please take a look into the module configuration docs. You can define global headers per API endpoint:

export default defineNuxtConfig({
  apiParty: {
    endpoints: {
      myApi: {
        url: process.env.MY_API_BASE_URL!,
        // Define global headers here. They will be used with every `$myApi` or `useMyApiData` call.
        headers: {
          Authorization: `Bearer ${process.env.MY_API_TOKEN}`
        }
      },
    }
  }
})
tacxou commented 1 year ago

What if I want to take my header from a blind in this case? Doesn't your approach work?