InvokeAI/invokeai/frontend/web/src/services/api/client.ts
psychedelicious e386b5dc53 feat(ui): api layer refactor
*migrate from `openapi-typescript-codegen` to `openapi-typescript` and `openapi-fetch`*

`openapi-typescript-codegen` is not very actively maintained - it's been over a year since the last update.
`openapi-typescript` and `openapi-fetch` are part of the actively maintained repo. key differences:

- provides a `fetch` client instead of `axios`, which means we need to be a bit more verbose with typing thunks
- fetch client is created at runtime and has a very nice typescript DX
- generates a single file with all types in it, from which we then extract individual types. i don't like how verbose this is, but i do like how it is more explicit.
- removed npm api generation scripts - now we have a single `typegen` script

overall i have more confidence in this new library.

*use nanostores for api base and token*

very simple reactive store for api base url and token. this was suggested in the `openapi-fetch` docs and i quite like the strategy.

*organise rtk-query api*

split out each endpoint (models, images, boards, boardImages) into their own api extensions. tidy!
2023-06-24 17:57:39 +10:00

34 lines
938 B
TypeScript

import { atom, computed } from 'nanostores';
import createClient from 'openapi-fetch';
import { paths } from 'services/api/schema';
/**
* We use nanostores to store the token and base url for very simple reactivity
*/
/**
* The user's auth token.
*/
export const $authToken = atom<string | undefined>();
/**
* The OpenAPI base url.
*/
export const $baseUrl = atom<string | undefined>();
/**
* Autogenerated, type-safe fetch client for the API. Used when RTK Query is not an option.
* Dynamically updates when the token or base url changes.
* Use `$client.get()` to get the client.
*
* @example
* const { get, post, del } = $client.get();
*/
export const $client = computed([$authToken, $baseUrl], (authToken, baseUrl) =>
createClient<paths>({
headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
// do not include `api/v1` in the base url for this client
baseUrl: `${baseUrl ?? ''}`,
})
);