2022-09-09 22:46:53 +00:00
|
|
|
import { PublicApi } from "~~/lib/api/public";
|
2022-10-07 02:54:09 +00:00
|
|
|
import { UserClient } from "~~/lib/api/user";
|
2022-09-09 22:46:53 +00:00
|
|
|
import { Requests } from "~~/lib/requests";
|
2022-09-01 22:32:03 +00:00
|
|
|
|
2022-09-13 03:36:22 +00:00
|
|
|
export type Observer = {
|
2023-02-05 21:12:54 +00:00
|
|
|
handler: (r: Response, req?: RequestInit) => void;
|
2022-09-13 03:36:22 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
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 {
|
2022-09-09 22:46:53 +00:00
|
|
|
const requests = new Requests("", "", {});
|
2022-09-01 22:32:03 +00:00
|
|
|
return new PublicApi(requests);
|
|
|
|
}
|
|
|
|
|
2022-10-07 02:54:09 +00:00
|
|
|
export function useUserApi(): UserClient {
|
2023-02-18 06:57:21 +00:00
|
|
|
const authCtx = useAuthContext();
|
2022-09-04 06:19:13 +00:00
|
|
|
|
2023-10-07 03:44:43 +00:00
|
|
|
const requests = new Requests("", "", {});
|
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) {
|
2023-03-23 05:52:25 +00:00
|
|
|
console.error("unauthorized request, invalidating session");
|
2023-02-18 06:57:21 +00:00
|
|
|
authCtx.invalidateSession();
|
2023-10-07 03:44:43 +00:00
|
|
|
if (window.location.pathname !== "/") {
|
|
|
|
window.location.href = "/";
|
|
|
|
}
|
2022-09-04 06:19:13 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-09-13 03:36:22 +00:00
|
|
|
for (const [_, observer] of Object.entries(observers)) {
|
|
|
|
requests.addResponseInterceptor(observer.handler);
|
|
|
|
}
|
|
|
|
|
2023-02-18 06:57:21 +00:00
|
|
|
return new UserClient(requests, authCtx.attachmentToken || "");
|
2022-09-01 22:32:03 +00:00
|
|
|
}
|