api.js 4.3 KB

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