video-flow-b/api/serversetting.ts

139 lines
3.9 KiB
TypeScript

import { BASE_URL } from "./constants";
import { post } from './request';
// 获取路演配置数据
export const fetchRoadshowConfigs = async () => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
try {
console.log('开始请求接口数据...');
const response = await fetch(BASE_URL + '/serversetting/roadshow-configs', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`接口请求失败: HTTP ${response.status} - ${response.statusText}`);
}
const result = await response.json();
console.log('接口返回数据:', result);
// 验证返回数据格式
if (result.code !== 0) {
throw new Error(`接口错误: ${result.message || '未知错误'} (code: ${result.code})`);
}
if (!result.successful) {
throw new Error(`接口调用不成功: ${result.message || '未知原因'}`);
}
if (!result.data || !Array.isArray(result.data) || result.data.length === 0) {
throw new Error('接口返回数据格式错误或为空');
}
// 验证数据结构
let validData: any[] = [];
result.data.forEach((item: any) => {
if (item) {
validData.push(JSON.parse(item));
}
});
if (validData.length === 0) {
throw new Error('接口返回的数据格式不正确');
}
console.log('成功获取并验证接口数据:', validData);
return validData;
} catch (error: unknown) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === 'AbortError') {
throw new Error('接口请求超时,请检查网络连接');
}
console.error('接口请求失败:', error);
throw error;
}
};
/**
* 根据服务端配置 code 拉取配置
* 约定返回结构:{ code, message, successful, data: { value: string(JSON) } }
*/
export interface ServerSettingVideoItem {
id: string;
title: string;
url: string;
cover?: string;
duration?: number;
sortOrder?: number;
}
export interface ServerSettingTabItem {
id: string;
title: string;
subtitle?: string;
status: number;
sortOrder?: number;
videos: ServerSettingVideoItem[];
}
export interface HomeTabItem {
subtitle: string;
title: string;
videos: string[];
}
export const fetchTabsByCode = async (code: string): Promise<HomeTabItem[]> => {
const res = await post<any>(`/api/server-setting/find_by_code`, { code });
if (!res || res.code !== 0 || !res.successful || !res.data) return [];
const raw = res.data.value;
if (typeof raw !== 'string' || raw.length === 0) return [];
try {
const parsed: ServerSettingTabItem[] = JSON.parse(raw);
return parsed
.filter((t) => t && t.status === 1)
.sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
.map((t) => ({
title: t.title,
subtitle: t.subtitle || '',
videos: (t.videos || [])
.sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
.map((v) => v.url)
.filter(Boolean),
}));
} catch {
return [];
}
};
/**
* 通用:按 code 获取服务端配置,并解析为指定类型
* 最简约实现:仅解析 res.data.value(JSON 字符串),失败返回默认值
*/
export const fetchSettingByCode = async <T = unknown>(
code: string,
defaultValue?: T
): Promise<T | undefined> => {
try {
const res = await post<any>(`/api/server-setting/find_by_code`, { code });
if (!res || res.code !== 0 || !res.successful || !res.data) return defaultValue;
const raw = res.data.value;
if (typeof raw !== 'string' || raw.length === 0) return defaultValue;
const parsed: T = JSON.parse(raw);
return parsed;
} catch {
return defaultValue;
}
};