homebox/frontend/composables/use-api.ts

32 lines
809 B
TypeScript
Raw Normal View History

2022-09-04 06:19:13 +00:00
import { PublicApi } from '~~/lib/api/public';
import { UserApi } from '~~/lib/api/user';
import { Requests } from '~~/lib/requests';
import { useAuthStore } from '~~/stores/auth';
2022-09-01 22:32:03 +00:00
2022-09-04 06:19:13 +00:00
function ApiDebugger(r: Response) {
2022-09-01 22:32:03 +00:00
console.table({
2022-09-04 06:19:13 +00:00
'Request Url': r.url,
'Response Status': r.status,
'Response Status Text': r.statusText,
2022-09-01 22:32:03 +00:00
});
}
export function usePublicApi(): PublicApi {
2022-09-04 06:19:13 +00:00
const requests = new Requests('', '', {});
2022-09-01 22:32:03 +00:00
return new PublicApi(requests);
}
export function useUserApi(): UserApi {
const authStore = useAuthStore();
2022-09-04 06:19:13 +00:00
const requests = new Requests('', () => authStore.token, {});
requests.addResponseInterceptor(ApiDebugger);
requests.addResponseInterceptor(r => {
if (r.status === 401) {
authStore.clearSession();
}
});
2022-09-01 22:32:03 +00:00
return new UserApi(requests);
}