mock.ts 7.15 KB
// Mock API 服务 - 用于开发测试

// 模拟延迟
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// Mock 用户数据
const mockUsers = [
  {
    id: "1",
    email: "test@example.com",
    password: "123456",
    realName: "测试用户",
    phone: "13800138000",
    role: "USER",
    status: "ACTIVE",
  },
];

// Mock API 函数
export const mockApi = {
  // 模拟登录
  async login(payload: {
    email: string;
    password: string;
    remember?: boolean;
  }) {
    await delay(1000); // 模拟网络延迟

    const user = mockUsers.find(
      (u) => u.email === payload.email && u.password === payload.password,
    );

    if (user) {
      return {
        success: true,
        data: {
          token: "mock-jwt-token-" + Date.now(),
          refreshToken: "mock-refresh-token-" + Date.now(),
          userId: user.id,
          email: user.email,
          role: user.role,
        },
      };
    } else {
      throw new Error("邮箱或密码错误");
    }
  },

  // 模拟注册
  async register(payload: {
    email: string;
    password: string;
    realName: string;
    phone: string;
    inviteCode?: string;
  }) {
    await delay(1500);

    // 检查邮箱是否已存在
    const existingUser = mockUsers.find((u) => u.email === payload.email);
    if (existingUser) {
      throw new Error("该邮箱已被注册");
    }

    // 模拟注册成功
    return {
      success: true,
      message: "注册成功,请查收激活邮件",
    };
  },

  // 模拟获取用户信息
  async getProfile() {
    await delay(500);

    return {
      success: true,
      data: {
        id: "1",
        username: "测试用户",
        email: "test@example.com",
        phone: "13800138000",
        avatar: "",
        status: "ACTIVE",
        role: "USER",
        createdAt: "2025-01-15T10:30:00Z",
        updatedAt: "2025-01-15T10:30:00Z",
      },
    };
  },

  // 模拟忘记密码
  async forgotPassword(payload: { email: string }) {
    await delay(1000);

    const user = mockUsers.find((u) => u.email === payload.email);
    if (!user) {
      throw new Error("该邮箱未注册");
    }

    return {
      success: true,
      message: "重置密码邮件已发送",
    };
  },

  // 模拟重发激活邮件
  async resendActivation(_email: string) {
    await delay(1000);

    return {
      success: true,
      message: "激活邮件已重发",
    };
  },

  // 模拟邮箱验证
  async verify(_token: string) {
    await delay(1000);

    return {
      success: true,
      data: {
        token: "mock-jwt-token-" + Date.now(),
        userId: "1",
        email: "test@example.com",
        role: "USER",
      },
    };
  },

  // 模拟刷新 token
  async refreshToken(_refreshToken: string) {
    await delay(500);

    return {
      success: true,
      data: {
        token: "mock-jwt-token-" + Date.now(),
        refreshToken: "mock-refresh-token-" + Date.now(),
        userId: "1",
        email: "test@example.com",
        role: "USER",
      },
    };
  },

  // 模拟登出
  async logout(_refreshToken: string) {
    await delay(300);

    return {
      success: true,
      message: "登出成功",
    };
  },
};

// 开发环境下的 Mock 拦截器
export const setupMockInterceptors = () => {
  if (import.meta.env.DEV) {
    console.log("🔧 Mock API 已启用");

    // 拦截所有 API 请求并返回 Mock 数据
    const originalFetch = window.fetch;
    window.fetch = async (url: RequestInfo | URL, options?: RequestInit) => {
      const urlString = url.toString();

      // 优先检查:直接放行 DeerFlow 相关请求
      if (
        urlString.includes("deerflow") ||
        urlString.includes(":8000") ||
        urlString.includes("linkmed.cc/deerflow")
      ) {
        console.log("✅ DeerFlow 请求放行:", urlString);
        return originalFetch(url, options);
      }

      // 只拦截后端 API(8383 端口)
      const shouldIntercept =
        urlString.includes("/api/") &&
        (urlString.includes(":8383") || urlString.includes("192.168.0.193"));

      if (shouldIntercept) {
        console.log("🎭 Mock API 拦截:", urlString);

        // 模拟不同的 API 响应
        if (urlString.includes("/users/login")) {
          const body = options?.body ? JSON.parse(options.body as string) : {};
          const result = await mockApi.login(body);
          return new Response(JSON.stringify(result.data), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }

        if (urlString.includes("/users/register")) {
          const body = options?.body ? JSON.parse(options.body as string) : {};
          const result = await mockApi.register(body);
          return new Response(JSON.stringify({ message: result.message }), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }

        if (urlString.includes("/users/profile")) {
          const result = await mockApi.getProfile();
          return new Response(JSON.stringify(result.data), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }

        if (urlString.includes("/users/password/forgot")) {
          const body = options?.body ? JSON.parse(options.body as string) : {};
          const result = await mockApi.forgotPassword(body);
          return new Response(JSON.stringify({ message: result.message }), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }

        if (urlString.includes("/users/resend-activation")) {
          const url = new URL(urlString);
          const email = url.searchParams.get("email");
          const result = await mockApi.resendActivation(email || "");
          return new Response(JSON.stringify({ message: result.message }), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }

        if (urlString.includes("/users/verify")) {
          const url = new URL(urlString);
          const token = url.searchParams.get("token");
          const result = await mockApi.verify(token || "");
          return new Response(JSON.stringify(result.data), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }

        if (urlString.includes("/users/refresh")) {
          const body = options?.body ? JSON.parse(options.body as string) : {};
          const result = await mockApi.refreshToken(body.refreshToken);
          return new Response(JSON.stringify(result.data), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }

        if (urlString.includes("/users/logout")) {
          const body = options?.body ? JSON.parse(options.body as string) : {};
          const result = await mockApi.logout(body.refreshToken);
          return new Response(JSON.stringify({ message: result.message }), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }
      }

      // 其他请求使用原始 fetch
      return originalFetch(url, options);
    };
  }
};