apity
apity copied to clipboard
feat: allow reconfiguring Apity after fetch operations creation
The Apity global singleton cannot be reconfigured after the first config along with defined operations. The reconfiguration does not take any effect.
Say we have configure apity and defined some fetch operations. And we set a Authorization
field in headers which should be passed to backend server.
export const apity = Apity.for<paths>();
apity.configure({
// Base URL to your API
baseUrl: '',
// RequestInit options, e.g. default headers
init: {
headers: { Authorization: `Bearer ${keycloak.token}` }
},
});
export const fetchTasks = apity.path('/tasks').method('get').create();
However, the token is short lived (typically 5 minutes) and routinely reacquired with a refresh token. Then we need to update the defaultInit
's headers. But calling apity.configure()
when acquires a new token does not take any effect. This is because in the following codes, init
is finalized when calling create()
in operation definition and any changes to defaultInit
afterward do not affect the finalized init
.
create: function (queryParams?: Record<string, true | 1>) {
const fn = createFetch((payload, realFetch, init) =>
fetchUrl({
baseUrl: baseUrl || '', // baseUrl is fixed here, should be composed lazily
path: path as string,
method: method as Method,
queryParams: Object.keys(queryParams || {}),
payload,
init: mergeRequestInit(defaultInit, init), // init is fixed here, should be composed lazily
realFetch: realFetch || fetch,
// ...
How to fix
This PR use an Object to store baseUrl
and init
, and Objects in JavaScript are passed by reference. Ane we lazily compose init
when inside fetchUrl
function instead of function declaration.
If this works, this would be greatly appreciated
edit: specify the headers in fetchTasks
works fine tbh
That's true, but what if there are hundreds of API endpoint, like fetchTask
, deleteTask
, fetchFoo
and etc. Then users have to pass their headers in every api calls. In this way, we can certainly reach backend servers with required headers, but the svelte code would be quite messy.
Looking forward to this getting merged
For the time being, we can use pnpm patch to apply this feature to apity.
edit: specify the headers in fetchTasks works fine tbh sorry.. how?