api.ts 1.4 KB

12345678910111213141516171819202122232425262728293031
  1. import type { APIRequestContext } from '@playwright/test';
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import { fileURLToPath } from 'node:url';
  5. import { BASE } from './env.js';
  6. /** 直接调后端(走 dev server 的 /api 代理):准备与清理测试数据用,不经过页面 */
  7. const API = new URL('/api', BASE).toString();
  8. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  9. const AUTH_FILE = path.join(__dirname, '../../playwright/.auth/user.json');
  10. /** setup 项目登录后存下的 token(v6 放在 localStorage 的 token 里) */
  11. export function token(): string {
  12. const state = JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8')) as {
  13. origins: { localStorage: { name: string; value: string }[] }[];
  14. };
  15. const t = state.origins.flatMap((o) => o.localStorage).find((i) => i.name === 'token')?.value;
  16. if (!t) throw new Error('playwright/.auth/user.json 里没有 token,setup 是否跑过?');
  17. return t;
  18. }
  19. /** `path` 从版本前缀写起,如 `/v3/discussions`、`/v2/sentence/{uid}` */
  20. export async function call(request: APIRequestContext, method: string, path: string, data?: object) {
  21. const res = await request.fetch(`${API}${path}`, {
  22. method,
  23. data,
  24. headers: { Authorization: `Bearer ${token()}`, Accept: 'application/json' },
  25. });
  26. return { status: res.status(), body: await res.json().catch(() => null) };
  27. }