import { useCallback, useMemo } from 'react'; import axios, { AxiosRequestConfig } from 'axios'; import { useAuth } from '../../context/AuthContext'; export interface V2ApiClient { get: (url: string, config?: AxiosRequestConfig) => Promise; post: (url: string, body?: unknown, config?: AxiosRequestConfig) => Promise; patch: (url: string, body?: unknown, config?: AxiosRequestConfig) => Promise; // PUT, because `SET collapsed` is an idempotent set of one field and the // shipped route (#1109) is PUT /api/messages/:id/collapsed. Added rather // than routed through `patch`: the verb the server registered is the verb // the client should send. put: (url: string, body?: unknown, config?: AxiosRequestConfig) => Promise; del: (url: string, config?: AxiosRequestConfig) => Promise; } export const useV2Api = (): V2ApiClient => { const { token } = useAuth(); const headers = useMemo(() => ( token ? { Authorization: `Bearer ${token}` } : {} ), [token]); const get = useCallback(async (url: string, config: AxiosRequestConfig = {}) => { const res = await axios.get(url, { ...config, headers: { ...headers, ...(config.headers || {}) } }); return res.data; }, [headers]); const post = useCallback(async (url: string, body?: unknown, config: AxiosRequestConfig = {}) => { const res = await axios.post(url, body, { ...config, headers: { ...headers, ...(config.headers || {}) } }); return res.data; }, [headers]); const patch = useCallback(async (url: string, body?: unknown, config: AxiosRequestConfig = {}) => { const res = await axios.patch(url, body, { ...config, headers: { ...headers, ...(config.headers || {}) } }); return res.data; }, [headers]); const put = useCallback(async (url: string, body?: unknown, config: AxiosRequestConfig = {}) => { const res = await axios.put(url, body, { ...config, headers: { ...headers, ...(config.headers || {}) } }); return res.data; }, [headers]); const del = useCallback(async (url: string, config: AxiosRequestConfig = {}) => { const res = await axios.delete(url, { ...config, headers: { ...headers, ...(config.headers || {}) } }); return res.data; }, [headers]); return useMemo(() => ({ get, post, patch, put, del, }), [get, post, patch, put, del]); };