apity icon indicating copy to clipboard operation
apity copied to clipboard

feat: allow reconfiguring Apity after fetch operations creation

Open fMeow opened this issue 1 year ago • 5 comments

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.

fMeow avatar Feb 08 '24 06:02 fMeow

If this works, this would be greatly appreciated

edit: specify the headers in fetchTasks works fine tbh

jchen42703 avatar Mar 09 '24 14:03 jchen42703

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.

fMeow avatar Mar 10 '24 12:03 fMeow

Looking forward to this getting merged

jonwalch avatar Mar 22 '24 20:03 jonwalch

For the time being, we can use pnpm patch to apply this feature to apity.

fMeow avatar May 08 '24 08:05 fMeow

edit: specify the headers in fetchTasks works fine tbh sorry.. how?

novecento avatar Jun 07 '24 13:06 novecento