Bromeo777 commited on
Commit
59a0d70
·
unverified ·
1 Parent(s): 6817115

Update api-client.ts

Browse files
Files changed (1) hide show
  1. src/lib/api-client.ts +29 -11
src/lib/api-client.ts CHANGED
@@ -17,7 +17,7 @@ async function request<T>(
17
  endpoint: string,
18
  options: RequestInit & { params?: Record<string, string> } = {}
19
  ): Promise<T> {
20
- const { params, headers, ...config } = options;
21
 
22
  // 1. Construct URL with Search Params
23
  const url = new URL(`${BASE_URL}${endpoint}`);
@@ -28,20 +28,38 @@ async function request<T>(
28
  // 2. Token Retrieval (Direct localStorage for non-React context utility)
29
  const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;
30
 
31
- // 3. Header Synthesis
32
- const authHeader = token ? { Authorization: `Bearer ${token}` } : {};
33
-
34
- // Don't set Content-Type if sending FormData (browser handles it)
35
  const isFormData = config.body instanceof FormData;
36
- const contentTypeHeader = isFormData ? {} : { "Content-Type": "application/json" };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  const finalConfig: RequestInit = {
39
  ...config,
40
- headers: {
41
- ...contentTypeHeader,
42
- ...authHeader,
43
- ...headers,
44
- },
45
  };
46
 
47
  try {
 
17
  endpoint: string,
18
  options: RequestInit & { params?: Record<string, string> } = {}
19
  ): Promise<T> {
20
+ const { params, headers: customHeaders, ...config } = options;
21
 
22
  // 1. Construct URL with Search Params
23
  const url = new URL(`${BASE_URL}${endpoint}`);
 
28
  // 2. Token Retrieval (Direct localStorage for non-React context utility)
29
  const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;
30
 
31
+ // 3. Header Synthesis - Build headers as Record<string, string>
32
+ const headers: Record<string, string> = {};
33
+
34
+ // Add Content-Type if not FormData
35
  const isFormData = config.body instanceof FormData;
36
+ if (!isFormData) {
37
+ headers["Content-Type"] = "application/json";
38
+ }
39
+
40
+ // Add Authorization if token exists
41
+ if (token) {
42
+ headers["Authorization"] = `Bearer ${token}`;
43
+ }
44
+
45
+ // Merge custom headers
46
+ if (customHeaders) {
47
+ if (customHeaders instanceof Headers) {
48
+ customHeaders.forEach((value, key) => {
49
+ headers[key] = value;
50
+ });
51
+ } else if (Array.isArray(customHeaders)) {
52
+ customHeaders.forEach(([key, value]) => {
53
+ headers[key] = value;
54
+ });
55
+ } else {
56
+ Object.assign(headers, customHeaders as Record<string, string>);
57
+ }
58
+ }
59
 
60
  const finalConfig: RequestInit = {
61
  ...config,
62
+ headers,
 
 
 
 
63
  };
64
 
65
  try {