drwpow / openapi-fetch

Ultra-fast fetching for TypeScript generated automatically from your OpenAPI schema
MIT License
65 stars 17 forks source link

dynamic loading of headers #16

Closed chiptus closed 1 year ago

chiptus commented 1 year ago

Description

I would love to be able to create a client but instead of providing a static config, provide something that can load the headers per request. For example we could use it to load the jwt token in-case the user is authenticated.

Proposal

createClient<paths>({
    headers: (headrs) => {
        const jwt = localStorageGet('JWT', '');
      if (!jwt) {
            return headers
      }

    return {
            ...headers
            Authorization: `Bearer ${jwt}`
       }

    }

})

Checklist

drwpow commented 1 year ago

This is something I think is outside the scope of this library, because it would encroach into state management which would not only bloat it out; it would also have to be an opinionated implementation that’s higher level than what this library is intended to do.

Here’s an example I’m actually using with nanostores, a universal signals library:

import { paths } from './v1';
import { atom, computed } from 'nanostores';

export const authToken = atom<string | undefined>();

export const client = computed(authToken, (currentToken) =>
  createClient<paths>({ headers: currentToken ? { Authorization: `Bearer ${currentToken}` } : {} })
);

someAuthMethod().then((token) => authToken.set(token));

client.get().get('/some-authenticated-url'); // will always pass auth headers if token is set

// note: the first `.get()` is part of nanostores; see docs

The same can be achieved with Preact Signals, Svelte Stores, Redux, etc. etc. Anything that’s reactive (just as long as it’s not export let client = createClient() since that will yield a temporary reference that won’t be updated on reassignment, but wrapping it in an object would work)

I think this is probably a good signal to include some of this in the docs. And hopefully this also illustrates that reactivity is something more opinionated / higher level than this fetch client.