/** * 统一 API 请求封装 * 提供 GET / POST / PUT / DELETE 方法,自动处理认证和错误 */ import { request, APIRequestContext } from '@playwright/test'; const BASE_URL = 'http://localhost:3000'; let apiContext: APIRequestContext; let authToken: string | null = null; let testUserId: string | null = null; /** 初始化 API 客户端 */ export async function initApiClient() { apiContext = await request.newContext({ baseURL: BASE_URL }); } /** 释放 API 客户端 */ export async function disposeApiClient() { if (apiContext) await apiContext.dispose(); } /** 设置认证 token */ export function setAuthToken(token: string, userId?: string) { authToken = token; if (userId) testUserId = userId; } /** 获取当前 token */ export function getAuthToken(): string | null { return authToken; } /** 获取当前测试用户 ID */ export function getTestUserId(): string { return testUserId || '1'; } /** 通用请求选项 */ function getOptions(method: string, data?: any): Record { const options: Record = { method, headers: { 'Content-Type': 'application/json' }, }; if (authToken) { options.headers['Authorization'] = `Bearer ${authToken}`; } if (data) { options.data = data; } return options; } /** API 响应类型 */ export interface ApiResponse { code: number; message: string; data: any; } /** GET 请求 */ export async function apiGet(path: string, params?: Record): Promise { let url = path; if (params) { const qs = new URLSearchParams(params).toString(); url = `${path}?${qs}`; } const res = await apiContext.get(url); const body = await res.json(); return { code: body.code ?? res.status(), message: body.message ?? '', data: body.data }; } /** POST 请求 */ export async function apiPost(path: string, data?: any): Promise { const res = await apiContext.post(path, getOptions('POST', data)); const body = await res.json(); return { code: body.code ?? res.status(), message: body.message ?? '', data: body.data }; } /** PUT 请求 */ export async function apiPut(path: string, data?: any): Promise { const res = await apiContext.put(path, getOptions('PUT', data)); const body = await res.json(); return { code: body.code ?? res.status(), message: body.message ?? '', data: body.data }; } /** DELETE 请求 */ export async function apiDelete(path: string): Promise { const res = await apiContext.delete(path, getOptions('DELETE')); const body = await res.json(); return { code: body.code ?? res.status(), message: body.message ?? '', data: body.data }; } /** 获取原始响应(用于检查状态码等) */ export async function apiRaw(method: string, path: string, data?: any) { return apiContext.fetch(path, getOptions(method, data)); }