1
0
Fork 1
mirror of https://github.com/hay-kot/homebox.git synced 2024-12-30 10:36:40 +00:00
homebox/frontend/composables/use-api.ts

48 lines
1.2 KiB
TypeScript
Raw Normal View History

import { PublicApi } from "~~/lib/api/public";
import { UserClient } from "~~/lib/api/user";
import { Requests } from "~~/lib/requests";
import { useAuthStore } from "~~/stores/auth";
2022-09-01 22:32:03 +00:00
export type Observer = {
handler: (r: Response) => void;
};
export type RemoveObserver = () => void;
const observers: Record<string, Observer> = {};
export function defineObserver(key: string, observer: Observer): RemoveObserver {
observers[key] = observer;
return () => {
delete observers[key];
};
}
2022-09-04 06:19:19 +00:00
function logger(r: Response) {
console.log(`${r.status} ${r.url} ${r.statusText}`);
2022-09-01 22:32:03 +00:00
}
export function usePublicApi(): PublicApi {
const requests = new Requests("", "", {});
2022-09-01 22:32:03 +00:00
return new PublicApi(requests);
}
export function useUserApi(): UserClient {
2022-09-01 22:32:03 +00:00
const authStore = useAuthStore();
2022-09-04 06:19:13 +00:00
const requests = new Requests("", () => authStore.token, {});
2022-09-04 06:19:19 +00:00
requests.addResponseInterceptor(logger);
2022-09-04 06:19:13 +00:00
requests.addResponseInterceptor(r => {
if (r.status === 401) {
authStore.clearSession();
}
});
for (const [_, observer] of Object.entries(observers)) {
requests.addResponseInterceptor(observer.handler);
}
return new UserClient(requests);
2022-09-01 22:32:03 +00:00
}