diff options
| author | Fuwn <[email protected]> | 2026-01-24 13:09:50 +0000 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2026-01-24 13:09:50 +0000 |
| commit | 396acf3bbbe00a192cb0ea0a9ccf91b1d8d2850b (patch) | |
| tree | b9df4ca6a70db45cfffbae6fdd7252e20fb8e93c /src/components/hooks/useApi.ts | |
| download | umami-main.tar.xz umami-main.zip | |
Created from https://vercel.com/new
Diffstat (limited to 'src/components/hooks/useApi.ts')
| -rw-r--r-- | src/components/hooks/useApi.ts | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/src/components/hooks/useApi.ts b/src/components/hooks/useApi.ts new file mode 100644 index 0000000..35cabd5 --- /dev/null +++ b/src/components/hooks/useApi.ts @@ -0,0 +1,67 @@ +import { useMutation, useQuery } from '@tanstack/react-query'; +import { useCallback } from 'react'; +import { getClientAuthToken } from '@/lib/client'; +import { SHARE_TOKEN_HEADER } from '@/lib/constants'; +import { type FetchResponse, httpDelete, httpGet, httpPost, httpPut } from '@/lib/fetch'; +import { useApp } from '@/store/app'; + +const selector = (state: { shareToken: { token?: string } }) => state.shareToken; + +async function handleResponse(res: FetchResponse): Promise<any> { + if (!res.ok) { + const { message, code, status } = res?.data?.error || {}; + + return Promise.reject(Object.assign(new Error(message), { code, status })); + } + return Promise.resolve(res.data); +} + +export function useApi() { + const shareToken = useApp(selector); + + const defaultHeaders = { + authorization: `Bearer ${getClientAuthToken()}`, + [SHARE_TOKEN_HEADER]: shareToken?.token, + }; + const basePath = process.env.basePath; + + const getUrl = (url: string) => { + return url.startsWith('http') ? url : `${basePath || ''}/api${url}`; + }; + + const getHeaders = (headers: any = {}) => { + return { ...defaultHeaders, ...headers }; + }; + + return { + get: useCallback( + async (url: string, params: object = {}, headers: object = {}) => { + return httpGet(getUrl(url), params, getHeaders(headers)).then(handleResponse); + }, + [httpGet], + ), + + post: useCallback( + async (url: string, params: object = {}, headers: object = {}) => { + return httpPost(getUrl(url), params, getHeaders(headers)).then(handleResponse); + }, + [httpPost], + ), + + put: useCallback( + async (url: string, params: object = {}, headers: object = {}) => { + return httpPut(getUrl(url), params, getHeaders(headers)).then(handleResponse); + }, + [httpPut], + ), + + del: useCallback( + async (url: string, params: object = {}, headers: object = {}) => { + return httpDelete(getUrl(url), params, getHeaders(headers)).then(handleResponse); + }, + [httpDelete], + ), + useQuery, + useMutation, + }; +} |