| 1 |
import React, { useMemo } from 'react' |
| 2 |
import axios from 'axios' |
| 3 |
import { createContextHook } from '../utils/hooks' |
| 4 |
import { REST_API_AXIOS_CONFIG } from '../utils/restAPI' |
| 5 |
import { buildSnippetsAPI } from '../utils/snippets/api' |
| 6 |
import type { SnippetsAPI } from '../utils/snippets/api' |
| 7 |
import type { PropsWithChildren } from 'react' |
| 8 |
import type { AxiosInstance, AxiosResponse } from 'axios' |
| 9 |
|
| 10 |
export interface RestAPIContext { |
| 11 |
api: RestAPI |
| 12 |
snippetsAPI: SnippetsAPI |
| 13 |
axiosInstance: AxiosInstance |
| 14 |
} |
| 15 |
|
| 16 |
export interface RestAPI { |
| 17 |
get: <T>(url: string) => Promise<T> |
| 18 |
post: <T>(url: string, data?: object) => Promise<T> |
| 19 |
put: <T>(url: string, data?: object) => Promise<T> |
| 20 |
del: <T>(url: string) => Promise<T> |
| 21 |
} |
| 22 |
|
| 23 |
const debugRequest = async <T, D = never>( |
| 24 |
method: 'GET' | 'POST' | 'PUT' | 'DELETE', |
| 25 |
url: string, |
| 26 |
doRequest: Promise<AxiosResponse<T, D>>, |
| 27 |
data?: D |
| 28 |
): Promise<T> => { |
| 29 |
console.debug(`${method} ${url}`, ...data ? [data] : []) |
| 30 |
const response = await doRequest |
| 31 |
console.debug('Response', response) |
| 32 |
return response.data |
| 33 |
} |
| 34 |
|
| 35 |
const buildRestAPI = (axiosInstance: AxiosInstance): RestAPI => ({ |
| 36 |
get: <T, >(url: string): Promise<T> => |
| 37 |
debugRequest('GET', url, axiosInstance.get<T, AxiosResponse<T, never>, never>(url)), |
| 38 |
|
| 39 |
post: <T, >(url: string, data?: object): Promise<T> => |
| 40 |
debugRequest('POST', url, axiosInstance.post<T, AxiosResponse<T, typeof data>, typeof data>(url, data), data), |
| 41 |
|
| 42 |
del: <T, >(url: string): Promise<T> => |
| 43 |
debugRequest('DELETE', url, axiosInstance.delete<T, AxiosResponse<T, never>, never>(url)), |
| 44 |
|
| 45 |
put: <T, >(url: string, data?: object): Promise<T> => |
| 46 |
debugRequest('PUT', url, axiosInstance.put<T, AxiosResponse<T, typeof data>, typeof data>(url, data), data) |
| 47 |
}) |
| 48 |
|
| 49 |
export const [RestAPIContext, useRestAPI] = createContextHook<RestAPIContext>('RestAPI') |
| 50 |
|
| 51 |
export const WithRestAPIContext: React.FC<PropsWithChildren> = ({ children }) => { |
| 52 |
const axiosInstance = useMemo(() => axios.create(REST_API_AXIOS_CONFIG), []) |
| 53 |
|
| 54 |
const api = useMemo(() => buildRestAPI(axiosInstance), [axiosInstance]) |
| 55 |
const snippetsAPI = useMemo(() => buildSnippetsAPI(api), [api]) |
| 56 |
|
| 57 |
const value: RestAPIContext = { api, snippetsAPI, axiosInstance } |
| 58 |
|
| 59 |
return <RestAPIContext.Provider value={value}>{children}</RestAPIContext.Provider> |
| 60 |
} |
| 61 |
|