-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathauth.ts
More file actions
35 lines (29 loc) · 1.04 KB
/
auth.ts
File metadata and controls
35 lines (29 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { auth } from "../firebase/firebase.js";
type RestMethod = "GET" | "POST" | "PUT" | "DELETE";
export const authFetch =
(method: RestMethod) => async (url: string, body?: any) => {
const user = auth.currentUser;
// If no user is logged in, you can handle it accordingly
if (!user) {
throw new Error("User not authenticated");
}
const token = await user.getIdToken();
const headers = new Headers();
headers.set("Authorization", `Bearer ${token}`);
// set headers based on method
if (method === "GET") {
headers.set("Accept", "application/json");
} else if (method === "POST" || method === "PUT") {
headers.set("Accept", "application/json");
headers.set("Content-Type", "application/json");
}
return fetch(url, {
method,
headers,
...(body && { body: JSON.stringify(body) }),
});
};
export const authGet = authFetch("GET");
export const authPost = authFetch("POST");
export const authPut = authFetch("PUT");
export const authDelete = authFetch("DELETE");