| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192 |
- import { createTestServer } from './test-server';
- export interface ApiClientOptions {
- baseURL?: string;
- headers?: Record<string, string>;
- authToken?: string;
- }
- export class ApiClient {
- private app: any;
- private options: ApiClientOptions;
- constructor(app: any, options: ApiClientOptions = {}) {
- this.app = app;
- this.options = {
- baseURL: 'http://localhost:3000',
- headers: {
- 'Content-Type': 'application/json',
- },
- ...options
- };
- if (this.options.authToken) {
- this.options.headers = {
- ...this.options.headers,
- 'Authorization': `Bearer ${this.options.authToken}`
- };
- }
- }
- /**
- * 发送GET请求
- */
- async get<T = any>(path: string, headers?: Record<string, string>): Promise<ApiResponse<T>> {
- const server = createTestServer(this.app);
- const response = await server.get(path, {
- ...this.options.headers,
- ...headers
- });
- return this.createResponse(response);
- }
- /**
- * 发送POST请求
- */
- async post<T = any>(path: string, data?: any, headers?: Record<string, string>): Promise<ApiResponse<T>> {
- const server = createTestServer(this.app);
- const response = await server.post(path, data, {
- ...this.options.headers,
- ...headers
- });
- return this.createResponse(response);
- }
- /**
- * 发送PUT请求
- */
- async put<T = any>(path: string, data?: any, headers?: Record<string, string>): Promise<ApiResponse<T>> {
- const server = createTestServer(this.app);
- const response = await server.put(path, data, {
- ...this.options.headers,
- ...headers
- });
- return this.createResponse(response);
- }
- /**
- * 发送DELETE请求
- */
- async delete<T = any>(path: string, headers?: Record<string, string>): Promise<ApiResponse<T>> {
- const server = createTestServer(this.app);
- const response = await server.delete(path, {
- ...this.options.headers,
- ...headers
- });
- return this.createResponse(response);
- }
- /**
- * 发送PATCH请求
- */
- async patch<T = any>(path: string, data?: any, headers?: Record<string, string>): Promise<ApiResponse<T>> {
- const server = createTestServer(this.app);
- const response = await server.patch(path, data, {
- ...this.options.headers,
- ...headers
- });
- return this.createResponse(response);
- }
- /**
- * 设置认证令牌
- */
- setAuthToken(token: string): void {
- this.options.authToken = token;
- if (this.options.headers) {
- this.options.headers.Authorization = `Bearer ${token}`;
- }
- }
- /**
- * 清除认证令牌
- */
- clearAuthToken(): void {
- this.options.authToken = undefined;
- if (this.options.headers) {
- delete this.options.headers.Authorization;
- }
- }
- /**
- * 添加请求头
- */
- setHeader(name: string, value: string): void {
- if (!this.options.headers) {
- this.options.headers = {};
- }
- this.options.headers[name] = value;
- }
- /**
- * 移除请求头
- */
- removeHeader(name: string): void {
- if (this.options.headers) {
- delete this.options.headers[name];
- }
- }
- private createResponse<T>(response: any): ApiResponse<T> {
- return {
- status: response.status,
- headers: response.headers,
- data: response.data,
- ok: response.status >= 200 && response.status < 300,
- json: async () => response.data,
- text: async () => typeof response.data === 'string' ? response.data : JSON.stringify(response.data)
- };
- }
- }
- export interface ApiResponse<T = any> {
- status: number;
- headers: Record<string, string>;
- data: T;
- ok: boolean;
- json: () => Promise<T>;
- text: () => Promise<string>;
- }
- /**
- * 创建API客户端工厂函数
- */
- export function createApiClient(app: any, options?: ApiClientOptions): ApiClient {
- return new ApiClient(app, options);
- }
- /**
- * 断言响应状态码
- */
- export function expectStatus(response: ApiResponse, expectedStatus: number): void {
- if (response.status !== expectedStatus) {
- throw new Error(`Expected status ${expectedStatus}, but got ${response.status}. Response: ${JSON.stringify(response.data)}`);
- }
- }
- /**
- * 断言响应包含特定字段
- */
- export function expectResponseToHave<T>(response: ApiResponse<T>, expectedFields: Partial<T>): void {
- for (const [key, value] of Object.entries(expectedFields)) {
- if ((response.data as any)[key] !== value) {
- throw new Error(`Expected field ${key} to be ${value}, but got ${(response.data as any)[key]}`);
- }
- }
- }
- /**
- * 断言响应包含特定结构
- */
- export function expectResponseStructure(response: ApiResponse, structure: Record<string, any>): void {
- for (const key of Object.keys(structure)) {
- if (!(key in response.data)) {
- throw new Error(`Expected response to have key: ${key}`);
- }
- }
- }
|