45 lines
1.0 KiB
TypeScript
45 lines
1.0 KiB
TypeScript
import { api as baseApi } from "shared/config";
|
|
|
|
type TokenGetter = () => string | null | undefined;
|
|
|
|
class HttpClient {
|
|
private getToken: TokenGetter = () => null;
|
|
|
|
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();
|