59 行
1.5 KiB
TypeScript
59 行
1.5 KiB
TypeScript
|
|
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||
|
|
import { getConfig } from './config'
|
||
|
|
|
||
|
|
const TOKEN_KEY = '@xuqm:token'
|
||
|
|
|
||
|
|
export async function _getToken(): Promise<string | null> {
|
||
|
|
return AsyncStorage.getItem(TOKEN_KEY)
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function _saveToken(token: string): Promise<void> {
|
||
|
|
return AsyncStorage.setItem(TOKEN_KEY, token)
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function _clearToken(): Promise<void> {
|
||
|
|
return AsyncStorage.removeItem(TOKEN_KEY)
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function apiRequest<T>(
|
||
|
|
path: string,
|
||
|
|
options: {
|
||
|
|
method?: string
|
||
|
|
body?: unknown
|
||
|
|
params?: Record<string, string>
|
||
|
|
skipAuth?: boolean
|
||
|
|
} = {},
|
||
|
|
): Promise<T> {
|
||
|
|
const config = getConfig()
|
||
|
|
|
||
|
|
let url = config.apiBaseUrl + path
|
||
|
|
if (options.params) {
|
||
|
|
const qs = new URLSearchParams(options.params).toString()
|
||
|
|
url += (url.includes('?') ? '&' : '?') + qs
|
||
|
|
}
|
||
|
|
|
||
|
|
const headers: Record<string, string> = {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
Accept: 'application/json',
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!options.skipAuth) {
|
||
|
|
const token = await _getToken()
|
||
|
|
if (token) headers['Authorization'] = `Bearer ${token}`
|
||
|
|
}
|
||
|
|
|
||
|
|
const res = await fetch(url, {
|
||
|
|
method: options.method ?? 'GET',
|
||
|
|
headers,
|
||
|
|
body: options.body ? JSON.stringify(options.body) : undefined,
|
||
|
|
})
|
||
|
|
|
||
|
|
if (!res.ok) {
|
||
|
|
const err = await res.json().catch(() => ({ message: res.statusText }))
|
||
|
|
throw new Error((err as { message?: string }).message ?? `HTTP ${res.status}`)
|
||
|
|
}
|
||
|
|
|
||
|
|
const json = await res.json()
|
||
|
|
return (json.data ?? json) as T
|
||
|
|
}
|