Skip to content

Commit e6587b1

Browse files
committed
色々修正
1 parent e177b43 commit e6587b1

File tree

1 file changed

+6
-20
lines changed

1 file changed

+6
-20
lines changed

web/firebase/auth/lib.ts

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,19 @@ import { app } from "../config";
55

66
export class ErrUnauthorized extends Error {}
77

8-
let user: User;
9-
let token: string;
10-
118
const auth = getAuth(app);
129

1310
// 認証状態の完了を待機するためのPromiseを作成
14-
const authInitialized = new Promise<void>((resolve) => {
11+
const token = new Promise<string>((resolve) => {
1512
onAuthStateChanged(auth, async (u: User | null) => {
1613
if (u != null) {
17-
user = u;
18-
token = await user.getIdToken();
14+
resolve(await u.getIdToken());
1915
}
20-
resolve();
2116
});
2217
});
2318

24-
async function refreshToken() {
25-
token = await user.getIdToken(true);
26-
}
27-
2819
export async function getIdToken(): Promise<IDToken> {
29-
await authInitialized;
30-
if (token) return token;
31-
await refreshToken();
32-
return token;
20+
return await token;
3321
}
3422

3523
type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
@@ -46,20 +34,18 @@ export async function credFetch(
4634
body?: unknown,
4735
): Promise<Response> {
4836
try {
49-
const idToken = await getIdToken();
37+
let idToken = await getIdToken();
5038
const init: RequestInit = { method };
5139
if (body) {
5240
init.body = JSON.stringify(body);
5341
init.headers = {
5442
"Content-Type": "application/json",
5543
};
5644
}
57-
58-
let res: Response;
59-
res = await fetch(`${path}?token=${idToken}`, init);
45+
let res = await fetch(`${path}?token=${idToken}`, init);
6046

6147
if (res.status === 401) {
62-
await refreshToken();
48+
idToken = await getIdToken();
6349
res = await fetch(`${path}?token=${idToken}`, init);
6450
}
6551

0 commit comments

Comments
 (0)