54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { fetch, FetchRequestInit } from 'expo/fetch';
|
|
import { storage } from '../storage';
|
|
|
|
const BASE_URL = 'https://api-test.mixvideo.bowong.cc';
|
|
|
|
export interface ApiRequestOptions extends FetchRequestInit {
|
|
params?: Record<string, string | number | boolean | undefined>;
|
|
}
|
|
|
|
export async function apiClient<T = any>(
|
|
endpoint: string,
|
|
options: ApiRequestOptions = {}
|
|
): Promise<T> {
|
|
const { params, ...fetchOptions } = options;
|
|
|
|
let url = `${BASE_URL}${endpoint}`;
|
|
|
|
if (params) {
|
|
const queryParams = new URLSearchParams();
|
|
Object.entries(params).forEach(([key, value]) => {
|
|
if (value !== undefined) {
|
|
queryParams.append(key, String(value));
|
|
}
|
|
});
|
|
const queryString = queryParams.toString();
|
|
if (queryString) {
|
|
url += `?${queryString}`;
|
|
}
|
|
}
|
|
|
|
const token = storage.getItem('bestaibest.better-auth.session_token');
|
|
|
|
const headers: any = {
|
|
'Content-Type': 'application/json',
|
|
...fetchOptions.headers,
|
|
};
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const response = await fetch(url, {
|
|
...fetchOptions,
|
|
headers,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.text();
|
|
throw new Error(`API Error: ${response.status} - ${error}`);
|
|
}
|
|
|
|
return response.json();
|
|
}
|