2026-04-21 22:07:29 +08:00
|
|
|
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
|
|
|
import { getConfig } from './config'
|
|
|
|
|
|
|
|
|
|
const TOKEN_KEY = '@xuqm_sdk_token'
|
2026-04-29 15:46:40 +08:00
|
|
|
const DEFAULT_API_URL = 'https://dev.xuqinmin.com'
|
2026-04-21 22:07:29 +08:00
|
|
|
|
|
|
|
|
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> } = {},
|
|
|
|
|
): Promise<T> {
|
|
|
|
|
const config = getConfig()
|
|
|
|
|
const token = await getToken()
|
|
|
|
|
|
2026-04-29 15:46:40 +08:00
|
|
|
let url = DEFAULT_API_URL.replace(/\/$/, '') + path
|
2026-04-21 22:07:29 +08:00
|
|
|
if (options.params) {
|
|
|
|
|
const qs = new URLSearchParams(options.params).toString()
|
|
|
|
|
url += (url.includes('?') ? '&' : '?') + qs
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const res = await fetch(url, {
|
|
|
|
|
method: options.method ?? 'GET',
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
Accept: 'application/json',
|
|
|
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
|
|
|
},
|
|
|
|
|
body: options.body ? JSON.stringify(options.body) : undefined,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
const err = await res.json().catch(() => ({ message: res.statusText }))
|
|
|
|
|
throw new Error(err.message ?? `HTTP ${res.status}`)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const json = await res.json()
|
|
|
|
|
return json.data ?? json
|
|
|
|
|
}
|