msw-handlers.ts 1.9 KB
import { http, HttpResponse, delay } from 'msw';

const BASE = '/api/v1';

export const handlers = [
  http.post(`${BASE}/auth/login`, async ({ request }) => {
    const body = (await request.json()) as { username: string; password: string; companyCode: string };

    if (body.companyCode === 'NOPE') {
      return HttpResponse.json(
        { code: 40004, message: '公司不存在或已删除', data: null, timestamp: Date.now() },
        { status: 400 },
      );
    }
    if (body.username === 'locked') {
      return HttpResponse.json(
        {
          code: 42301,
          message: '账号已锁定,请稍后再试',
          data: { lockUntil: '2030-01-01T12:00:00' },
          timestamp: Date.now(),
        },
        { status: 423 },
      );
    }
    if (body.username === 'deleted') {
      return HttpResponse.json(
        { code: 40103, message: '账号已被作废,禁止登录', data: null, timestamp: Date.now() },
        { status: 401 },
      );
    }
    if (body.username !== 'alice' || body.password !== 'Password1!') {
      return HttpResponse.json(
        { code: 40101, message: '用户名或密码错误', data: null, timestamp: Date.now() },
        { status: 401 },
      );
    }

    return HttpResponse.json(
      {
        code: 200,
        message: '操作成功',
        data: {
          accessToken: 'fake-jwt',
          tokenType: 'Bearer',
          expiresInSec: 7200,
          userInfo: {
            userId: 1,
            username: 'alice',
            userType: 'NORMAL',
            language: 'zh-CN',
            employeeName: '张三',
            companyCode: body.companyCode,
          },
        },
        timestamp: Date.now(),
      },
      { status: 200 },
    );
  }),

  // Generic network-error stub for tests that pass requestUrl = "/network-error"
  http.post(`${BASE}/network-error`, async () => {
    await delay(50);
    return HttpResponse.error();
  }),
];