PluginProbe
Code Snippets / 3.9.1
Code Snippets v3.9.1
3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 3.0.1 All 64 releases
code-snippets / js / hooks / useRestAPI.tsx

useRestAPI.tsx in Code Snippets 3.9.1, at js/hooks/useRestAPI.tsx

61 lines 2.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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