replaced all react-query usages with new hooks + removed react-query

This commit is contained in:
dswbx
2024-12-13 17:36:09 +01:00
parent 8c91dff94d
commit 1631bbb754
23 changed files with 148 additions and 644 deletions

View File

@@ -1,3 +1,4 @@
import type { SafeUser } from "auth";
import { AuthApi } from "auth/api/AuthApi";
import { DataApi } from "data/api/DataApi";
import { decode } from "hono/jwt";
@@ -5,7 +6,7 @@ import { omit } from "lodash-es";
import { MediaApi } from "media/api/MediaApi";
import { SystemApi } from "modules/SystemApi";
export type TApiUser = object;
export type TApiUser = SafeUser;
declare global {
interface Window {
@@ -24,6 +25,12 @@ export type ApiOptions = {
localStorage?: boolean;
};
export type AuthState = {
token?: string;
user?: TApiUser;
verified: boolean;
};
export class Api {
private token?: string;
private user?: TApiUser;
@@ -50,6 +57,10 @@ export class Api {
this.buildApis();
}
get baseUrl() {
return this.options.host;
}
get tokenKey() {
return this.options.key ?? "auth";
}
@@ -85,7 +96,11 @@ export class Api {
updateToken(token?: string, rebuild?: boolean) {
this.token = token;
this.user = token ? omit(decode(token).payload as any, ["iat", "iss", "exp"]) : undefined;
if (token) {
this.user = omit(decode(token).payload as any, ["iat", "iss", "exp"]) as any;
} else {
this.user = undefined;
}
if (this.options.localStorage) {
const key = this.tokenKey;
@@ -105,7 +120,7 @@ export class Api {
return this;
}
getAuthState() {
getAuthState(): AuthState {
return {
token: this.token,
user: this.user,
@@ -113,6 +128,20 @@ export class Api {
};
}
async verifyAuth() {
try {
const res = await this.auth.me();
if (!res.ok || !res.body.user) {
throw new Error();
}
this.markAuthVerified(true);
} catch (e) {
this.markAuthVerified(false);
this.updateToken(undefined);
}
}
getUser(): TApiUser | null {
return this.user || null;
}