File size: 1,396 Bytes
42d8fb8
9a9d18a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42d8fb8
 
9a9d18a
 
 
 
 
 
 
 
 
42d8fb8
9a9d18a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import React, { createContext, useContext, ReactNode } from "react";

interface ApiContextType {
  baseUrl: string;
  wsBaseUrl: string;
  fetchWithHeaders: (url: string, options?: RequestInit) => Promise<Response>;
}

const ApiContext = createContext<ApiContextType | undefined>(undefined);

const DEFAULT_LOCALHOST = "http://localhost:8000";
const DEFAULT_WS_LOCALHOST = "ws://localhost:8000";

interface ApiProviderProps {
  children: ReactNode;
}

export const ApiProvider: React.FC<ApiProviderProps> = ({ children }) => {
  const baseUrl = DEFAULT_LOCALHOST;
  const wsBaseUrl = DEFAULT_WS_LOCALHOST;

  // Enhanced fetch function that automatically includes necessary headers
  const fetchWithHeaders = async (
    url: string,
    options: RequestInit = {}
  ): Promise<Response> => {
    const enhancedOptions: RequestInit = {
      ...options,
      headers: {
        "Content-Type": "application/json",
        ...options.headers,
      },
    };

    return fetch(url, enhancedOptions);
  };

  return (
    <ApiContext.Provider
      value={{
        baseUrl,
        wsBaseUrl,
        fetchWithHeaders,
      }}
    >
      {children}
    </ApiContext.Provider>
  );
};

export const useApi = (): ApiContextType => {
  const context = useContext(ApiContext);
  if (context === undefined) {
    throw new Error("useApi must be used within an ApiProvider");
  }
  return context;
};