All files / services/api/core helpers.ts

47.25% Statements 43/91
29.11% Branches 23/79
50% Functions 12/24
45.12% Lines 37/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248                        9x 12x           9x 12x             14x 2x     13x 5x 5x 8x 8x   5x     8x             11x 2x     10x 5x 5x 8x 8x   5x     5x           9x                 9x                 9x 3x 1x             2x 1x     1x 1x 1x                         9x                                                                                                                                                                                                                 9x 6x           9x             9x                                
/**
 * API 服务核心工具函数
 * 统一的数据转换、错误处理等
 */
 
import { logger } from '@/src/utils/logger';
 
import type { ApiErrorDetail, ApiResponse, PaginatedResponse } from './types';
 
/**
 * snake_case 转 camelCase
 */
export const snakeToCamel = (str: string): string => {
  return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
};
 
/**
 * camelCase 转 snake_case
 */
export const camelToSnake = (str: string): string => {
  return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
};
 
/**
 * 递归转换对象的所有 key 为 camelCase
 */
export function toCamelCase<T>(obj: unknown): T {
  if (Array.isArray(obj)) {
    return obj.map((item) => toCamelCase(item)) as unknown as T;
  }
 
  if (obj !== null && typeof obj === 'object' && !(obj instanceof Date)) {
    const result: Record<string, unknown> = {};
    for (const key of Object.keys(obj)) {
      const camelKey = snakeToCamel(key);
      result[camelKey] = toCamelCase((obj as Record<string, unknown>)[key]);
    }
    return result as T;
  }
 
  return obj as T;
}
 
/**
 * 递归转换对象的所有 key 为 snake_case
 */
export function toSnakeCase<T>(obj: unknown): T {
  if (Array.isArray(obj)) {
    return obj.map((item) => toSnakeCase(item)) as unknown as T;
  }
 
  if (obj !== null && typeof obj === 'object' && !(obj instanceof Date)) {
    const result: Record<string, unknown> = {};
    for (const key of Object.keys(obj)) {
      const snakeKey = camelToSnake(key);
      result[snakeKey] = toSnakeCase((obj as Record<string, unknown>)[key]);
    }
    return result as T;
  }
 
  return obj as T;
}
 
/**
 * 包装成功响应
 */
export const wrapSuccess = <T>(data: T): ApiResponse<T> => ({
  data,
  error: null,
  success: true,
});
 
/**
 * 包装错误响应
 */
export const wrapError = <T>(error: ApiErrorDetail): ApiResponse<T> => ({
  data: null,
  error,
  success: false,
});
 
/**
 * 从错误对象创建 ApiErrorDetail
 */
export const createErrorDetail = (error: unknown): ApiErrorDetail => {
  if (error instanceof Error) {
    return {
      message: error.message,
      code: (error as Error & { code?: string }).code,
      details: error,
    };
  }
 
  if (typeof error === 'string') {
    return { message: error };
  }
 
  Eif (error && typeof error === 'object') {
    const err = error as Record<string, unknown>;
    return {
      message: (err.message as string) || (err.detail as string) || '操作失败',
      code: err.code as string,
      details: err,
    };
  }
 
  return { message: '未知错误' };
};
 
/**
 * 统一的响应包装函数
 */
export const wrapResponse = <T>(data: T | null, error: unknown): ApiResponse<T> => {
  if (error) {
    return wrapError(createErrorDetail(error));
  }
  return wrapSuccess(data as T);
};
 
/**
 * 转换后端分页响应为统一格式
 */
export function normalizePaginatedResponse<T>(
  response: Record<string, unknown>,
  page: number = 1,
  pageSize: number = 20
): PaginatedResponse<T> {
  const results =
    (response.results as unknown[]) ||
    (response.items as unknown[]) ||
    (response.data as unknown[]) ||
    [];
  const count = (response.count as number) || (response.total as number) || results.length;
 
  return {
    results: Array.isArray(results) ? results.map((item) => toCamelCase<T>(item)) : [],
    count,
    page,
    pageSize,
    totalPages: Math.ceil(count / pageSize),
    next: (response.next as string) || null,
    previous: (response.previous as string) || null,
  };
}
 
/**
 * 从响应中提取数据(处理嵌套结构)
 */
export function extractData<T>(response: unknown, key?: string): T {
  if (response && typeof response === 'object') {
    const resp = response as Record<string, unknown>;
 
    if (key && key in resp) {
      return toCamelCase<T>(resp[key]);
    }
 
    // 尝试常见的嵌套 key
    const commonKeys = ['data', 'result', 'item', 'record'];
    for (const k of commonKeys) {
      if (k in resp) {
        return toCamelCase<T>(resp[k]);
      }
    }
  }
 
  return toCamelCase<T>(response);
}
 
/**
 * 从响应中提取列表数据
 */
export function extractList<T>(response: unknown, key?: string): T[] {
  if (response && typeof response === 'object') {
    const resp = response as Record<string, unknown>;
 
    if (key && key in resp) {
      const list = resp[key];
      if (Array.isArray(list)) {
        return list.map((item) => toCamelCase<T>(item));
      }
    }
 
    // 尝试常见的列表 key
    const commonKeys = ['results', 'items', 'data', 'list', 'records'];
    for (const k of commonKeys) {
      if (k in resp) {
        const list = resp[k];
        if (Array.isArray(list)) {
          return list.map((item) => toCamelCase<T>(item));
        }
      }
    }
  }
 
  // 如果响应本身是数组
  if (Array.isArray(response)) {
    return response.map((item) => toCamelCase<T>(item));
  }
 
  return [];
}
 
/**
 * 安全解析 Schema(带错误处理)
 */
export function safeParseSchema<T>(data: unknown, schema: { parse: (data: unknown) => T }): T {
  try {
    return schema.parse(data);
  } catch (error) {
    logger.error('Schema 验证失败', error as Error, { data });
    throw new Error('服务器返回数据格式错误');
  }
}
 
/**
 * 开发环境日志
 */
export const devLog = (message: string, data?: unknown): void => {
  logger.debug(`[API] ${message}`, data !== undefined ? { data } : undefined);
};
 
/**
 * 开发环境错误日志
 */
export const devError = (message: string, error?: unknown): void => {
  logger.error(`[API] ${message}`, error as Error);
};
 
/**
 * 构建查询字符串
 */
export const buildQueryString = (params: Record<string, unknown>): string => {
  const searchParams = new URLSearchParams();
 
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== '') {
      if (Array.isArray(value)) {
        searchParams.append(key, value.join(','));
      } else {
        searchParams.append(key, String(value));
      }
    }
  });
 
  const queryString = searchParams.toString();
  return queryString ? `?${queryString}` : '';
};