2022-09-09 14:46:53 -08:00
|
|
|
import { PublicApi } from "~~/lib/api/public";
|
2022-10-06 18:54:09 -08:00
|
|
|
import { UserClient } from "~~/lib/api/user";
|
2022-09-09 14:46:53 -08:00
|
|
|
import { Requests } from "~~/lib/requests";
|
|
|
|
import { useAuthStore } from "~~/stores/auth";
|
2022-09-01 14:32:03 -08:00
|
|
|
|
2022-09-12 19:36:22 -08: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-03 22:19:19 -08:00
|
|
|
function logger(r: Response) {
|
|
|
|
console.log(`${r.status} ${r.url} ${r.statusText}`);
|
2022-09-01 14:32:03 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
export function usePublicApi(): PublicApi {
|
2022-09-09 14:46:53 -08:00
|
|
|
const requests = new Requests("", "", {});
|
2022-09-01 14:32:03 -08:00
|
|
|
return new PublicApi(requests);
|
|
|
|
}
|
|
|
|
|
2022-10-06 18:54:09 -08:00
|
|
|
export function useUserApi(): UserClient {
|
2022-09-01 14:32:03 -08:00
|
|
|
const authStore = useAuthStore();
|
2022-09-03 22:19:13 -08:00
|
|
|
|
2022-09-09 14:46:53 -08:00
|
|
|
const requests = new Requests("", () => authStore.token, {});
|
2022-09-03 22:19:19 -08:00
|
|
|
requests.addResponseInterceptor(logger);
|
2022-09-03 22:19:13 -08:00
|
|
|
requests.addResponseInterceptor(r => {
|
|
|
|
if (r.status === 401) {
|
|
|
|
authStore.clearSession();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-09-12 19:36:22 -08:00
|
|
|
for (const [_, observer] of Object.entries(observers)) {
|
|
|
|
requests.addResponseInterceptor(observer.handler);
|
|
|
|
}
|
|
|
|
|
2022-12-03 10:55:00 -09:00
|
|
|
return new UserClient(requests, authStore.attachmentToken);
|
2022-09-01 14:32:03 -08:00
|
|
|
}
|