api-client.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Pure builders for 3x-ui panel API requests. The panel exposes every endpoint
  2. // under /panel/api/* and authenticates with `Authorization: Bearer <token>`
  3. // (reference/api/authentication). Emits a ready cURL command and a fetch()
  4. // snippet. No React/DOM imports.
  5. export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
  6. export interface ApiRequestInput {
  7. baseUrl: string;
  8. token: string;
  9. path: string; // e.g. /panel/api/inbounds/list
  10. method: HttpMethod;
  11. body?: string; // JSON string, for POST/PUT
  12. }
  13. export function normalizeBase(baseUrl: string): string {
  14. return baseUrl.trim().replace(/\/+$/, '');
  15. }
  16. export function joinUrl(baseUrl: string, path: string): string {
  17. const base = normalizeBase(baseUrl);
  18. const p = path.trim().startsWith('/') ? path.trim() : `/${path.trim()}`;
  19. return `${base}${p}`;
  20. }
  21. function hasBody(i: ApiRequestInput): boolean {
  22. return (i.method === 'POST' || i.method === 'PUT') && !!i.body && i.body.trim().length > 0;
  23. }
  24. export function buildCurl(i: ApiRequestInput): string {
  25. const url = joinUrl(i.baseUrl, i.path);
  26. const lines = [`curl -X ${i.method} '${url}'`, ` -H 'Authorization: Bearer ${i.token}'`];
  27. if (hasBody(i)) {
  28. lines.push(` -H 'Content-Type: application/json'`);
  29. lines.push(` --data '${i.body!.trim()}'`);
  30. }
  31. return lines.join(' \\\n');
  32. }
  33. export function buildFetchSnippet(i: ApiRequestInput): string {
  34. const url = joinUrl(i.baseUrl, i.path);
  35. const headers = [`'Authorization': 'Bearer ${i.token}'`];
  36. if (hasBody(i)) headers.push(`'Content-Type': 'application/json'`);
  37. const opts = [`method: '${i.method}'`, `headers: { ${headers.join(', ')} }`];
  38. if (hasBody(i)) opts.push(`body: JSON.stringify(${i.body!.trim()})`);
  39. return `await fetch('${url}', {\n ${opts.join(',\n ')},\n});`;
  40. }