// API配置文件 - 统一管理所有API相关配置
|
export const API_CONFIG = {
|
// 基础URL配置
|
BASE_URL: '/api',
|
|
// GraphQL端点
|
GRAPHQL_ENDPOINT: '/api/graphql',
|
|
// 其他API端点
|
ENDPOINTS: {
|
MEDIA_UPLOAD: '/api/media/upload',
|
MEDIA_DOWNLOAD: '/api/media/download',
|
WECHAT_LOGIN: '/api/wechat/login',
|
WECHAT_PHONE: '/api/wechat/phone'
|
}
|
}
|
|
// GraphQL请求工具函数
|
export const graphqlRequest = async (query: string, variables: any = {}) => {
|
console.log('=== GraphQL请求开始 ===');
|
console.log('请求端点:', API_CONFIG.GRAPHQL_ENDPOINT);
|
console.log('查询语句:', query);
|
console.log('变量:', variables);
|
|
// 获取JWT token
|
const { getToken } = await import('@/utils/auth');
|
const token = getToken();
|
console.log('JWT Token:', token ? '已获取' : '未获取');
|
|
const headers: Record<string, string> = {
|
'Content-Type': 'application/json',
|
};
|
if (token) {
|
headers['Authorization'] = `Bearer ${token}`;
|
}
|
console.log('请求头:', headers);
|
|
const requestBody = JSON.stringify({
|
query,
|
variables,
|
});
|
console.log('请求体:', requestBody);
|
|
try {
|
const response = await fetch(API_CONFIG.GRAPHQL_ENDPOINT, {
|
method: 'POST',
|
headers: headers,
|
body: requestBody,
|
})
|
|
console.log('响应状态:', response.status);
|
console.log('响应状态文本:', response.statusText);
|
|
if (!response.ok) {
|
throw new Error(`HTTP error! status: ${response.status}`)
|
}
|
|
const result = await response.json()
|
console.log('响应结果:', result);
|
|
if (result.errors) {
|
console.error('GraphQL错误:', result.errors);
|
throw new Error(result.errors[0].message)
|
}
|
|
console.log('返回数据:', result.data);
|
return result.data
|
} catch (error) {
|
console.error('=== GraphQL请求失败 ===');
|
console.error('错误详情:', error);
|
throw error;
|
}
|
}
|
|
// 通用API请求工具函数
|
export const apiRequest = async (endpoint: string, options: RequestInit = {}) => {
|
const url = endpoint.startsWith('http') ? endpoint : `${API_CONFIG.BASE_URL}${endpoint}`
|
|
const response = await fetch(url, {
|
headers: {
|
'Content-Type': 'application/json',
|
...options.headers,
|
},
|
...options,
|
})
|
|
if (!response.ok) {
|
throw new Error(`HTTP error! status: ${response.status}`)
|
}
|
|
return response.json()
|
}
|