http.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const root = import.meta.env.PROD ? '': '/api';
  2. const service = (uri, data, success, failure) => {
  3. post(uri, data, json => {
  4. if (json.code === 0 && success) {
  5. success(json.data);
  6. } else if (failure) {
  7. failure(json);
  8. }
  9. }, failure);
  10. }
  11. const post = (uri, body, success, failure) => {
  12. let header = {};
  13. psid(header);
  14. fetch(root + uri, {
  15. method: 'POST',
  16. headers: header,
  17. body: JSON.stringify(body)
  18. }).then(response => {
  19. if (uri === '/user/sign-out')
  20. localStorage.removeItem('photon-session-id');
  21. if (response.ok && success)
  22. response.json().then(success);
  23. }).catch(error => {
  24. if (failure)
  25. failure(error);
  26. });
  27. }
  28. const upload = (name, file, fileName, success, progress) => {
  29. let xhr = new XMLHttpRequest();
  30. xhr.upload.addEventListener('progress', event => {
  31. if (progress)
  32. progress(Math.round(100 * event.loaded / event.total));
  33. });
  34. xhr.addEventListener('load', event => {
  35. if (success)
  36. success(JSON.parse(xhr.responseText));
  37. });
  38. xhr.open('POST', root + '/photon/ctrl-http/upload');
  39. let header = {};
  40. psid(header);
  41. for (let key in header)
  42. xhr.setRequestHeader(key, header[key]);
  43. let body = new FormData();
  44. if (fileName)
  45. body.append(name, file, fileName);
  46. else
  47. body.append(name, file);
  48. xhr.send(body);
  49. }
  50. const psid = (header) => {
  51. // localStorage.setItem('photon-session-id', 'bh4n8magnjwix9q0k51utrdy0uk9gpuqfp4ssn0z8xdna0nlaq09xdugawveuq3u'); // delete-on-build
  52. let psid = localStorage.getItem('photon-session-id');
  53. if (!psid) {
  54. psid = '';
  55. while (psid.length < 64) psid += Math.random().toString(36).substring(2);
  56. psid = psid.substring(0, 64);
  57. localStorage.setItem('photon-session-id', psid);
  58. }
  59. header['photon-session-id'] = psid;
  60. }
  61. const url = uri => {
  62. if (!uri)
  63. return null;
  64. if (uri.indexOf('://') > -1)
  65. return uri;
  66. return root + uri;
  67. }
  68. export {
  69. post,
  70. service,
  71. upload,
  72. url,
  73. }