fix(auth): fix circular import problem by changing the way the authHttpClient gets accessToken; replace individual calls mocks with the common ones
This commit is contained in:
@@ -1,25 +1,44 @@
|
||||
import { useAuthStore } from "../../../model";
|
||||
import { api as baseApi } from "shared/config";
|
||||
|
||||
// Extend base API with authentication hooks
|
||||
export const api = baseApi.extend({
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
(request) => {
|
||||
const token = useAuthStore.getState().accessToken;
|
||||
type TokenGetter = () => string | null | undefined;
|
||||
|
||||
if (token) {
|
||||
request.headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
class HttpClient {
|
||||
private getToken: TokenGetter = () => null;
|
||||
|
||||
return request;
|
||||
},
|
||||
],
|
||||
afterResponse: [
|
||||
async (request, options, response) => {
|
||||
// Refresh token logic
|
||||
return response;
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
setTokenGetter(fn: TokenGetter) {
|
||||
this.getToken = fn;
|
||||
}
|
||||
|
||||
// Extend base API with authentication hooks
|
||||
private instance = baseApi.extend({
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
(request) => {
|
||||
const token = this.getToken();
|
||||
|
||||
if (token) {
|
||||
request.headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
|
||||
return request;
|
||||
},
|
||||
],
|
||||
afterResponse: [
|
||||
async (request, options, response) => {
|
||||
// Refresh token logic
|
||||
return response;
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
get = (url: string, options?: Parameters<typeof this.instance.get>[1]) => {
|
||||
return this.instance.get(url, options);
|
||||
};
|
||||
|
||||
post = (url: string, options?: Parameters<typeof this.instance.post>[1]) => {
|
||||
return this.instance.post(url, options);
|
||||
};
|
||||
}
|
||||
|
||||
export const authHttpClient = new HttpClient();
|
||||
|
||||
Reference in New Issue
Block a user