api.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. (function () {
  2. const TOKEN_KEY = 'pouchlab.token.v1';
  3. function token() {
  4. try { return localStorage.getItem(TOKEN_KEY) || ''; } catch (e) { return ''; }
  5. }
  6. function setToken(v) {
  7. try {
  8. if (v) localStorage.setItem(TOKEN_KEY, v);
  9. else localStorage.removeItem(TOKEN_KEY);
  10. } catch (e) {}
  11. }
  12. function request(method, path, body, opts) {
  13. opts = opts || {};
  14. const headers = {};
  15. if (body !== undefined) headers['Content-Type'] = 'application/json';
  16. const t = token();
  17. if (t) headers['Authorization'] = 'Bearer ' + t;
  18. const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
  19. const timer = controller ? setTimeout(function () { controller.abort(); }, opts.timeout || 30000) : null;
  20. return fetch('/api' + path, {
  21. method: method,
  22. headers: headers,
  23. body: body !== undefined ? JSON.stringify(body) : undefined,
  24. signal: controller ? controller.signal : undefined
  25. }).then(function (res) {
  26. if (timer) clearTimeout(timer);
  27. if (res.status === 401) {
  28. setToken('');
  29. document.dispatchEvent(new CustomEvent('pl:auth-expired'));
  30. }
  31. return res.json().catch(function () { return {}; }).then(function (data) {
  32. if (!res.ok) {
  33. const err = new Error(data.detail || ('请求失败(' + res.status + ')'));
  34. err.status = res.status;
  35. throw err;
  36. }
  37. return data;
  38. });
  39. }, function (e) {
  40. if (timer) clearTimeout(timer);
  41. if (e && e.name === 'AbortError') {
  42. const err = new Error('请求超时,请重试');
  43. err.network = true;
  44. throw err;
  45. }
  46. const err = new Error('无法连接服务器');
  47. err.network = true;
  48. throw err;
  49. });
  50. }
  51. // 带鉴权的文件下载(DXF/预览图/设计稿),转为浏览器下载
  52. function download(path, filename) {
  53. const t = token();
  54. return fetch('/api' + path, { headers: t ? { Authorization: 'Bearer ' + t } : {} }).then(function (res) {
  55. if (!res.ok) {
  56. return res.json().catch(function () { return {}; }).then(function (d) {
  57. throw new Error(d.detail || '下载失败(' + res.status + ')');
  58. });
  59. }
  60. return res.blob();
  61. }).then(function (blob) {
  62. const url = URL.createObjectURL(blob);
  63. const a = document.createElement('a');
  64. a.href = url;
  65. a.download = filename || '';
  66. document.body.appendChild(a);
  67. a.click();
  68. a.remove();
  69. setTimeout(function () { URL.revokeObjectURL(url); }, 4000);
  70. });
  71. }
  72. // SVG 字符串 → PNG dataURL(下单时生成本地预览,服务端与管理后台直接展示)
  73. function svgToPng(svg, maxW) {
  74. return new Promise(function (resolve, reject) {
  75. const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' });
  76. const url = URL.createObjectURL(blob);
  77. const img = new Image();
  78. img.onload = function () {
  79. const scale = Math.min(1, (maxW || 1000) / (img.width || 1));
  80. const canvas = document.createElement('canvas');
  81. canvas.width = Math.max(1, Math.round((img.width || 1) * scale));
  82. canvas.height = Math.max(1, Math.round((img.height || 1) * scale));
  83. const ctx = canvas.getContext('2d');
  84. ctx.fillStyle = '#ffffff';
  85. ctx.fillRect(0, 0, canvas.width, canvas.height);
  86. ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  87. URL.revokeObjectURL(url);
  88. resolve(canvas.toDataURL('image/png'));
  89. };
  90. img.onerror = function () {
  91. URL.revokeObjectURL(url);
  92. reject(new Error('预览图生成失败'));
  93. };
  94. img.src = url;
  95. });
  96. }
  97. window.PL = window.PL || {};
  98. window.PL.api = {
  99. token: token,
  100. setToken: setToken,
  101. request: request,
  102. download: download,
  103. svgToPng: svgToPng,
  104. get: function (p, o) { return request('GET', p, undefined, o); },
  105. post: function (p, b, o) { return request('POST', p, b, o); },
  106. patch: function (p, b, o) { return request('PATCH', p, b, o); }
  107. };
  108. })();