index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright 2010-2024 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. * author: gildas.lormeau <at> gmail.com
  5. * author: dcardin2007 <at> gmail.com
  6. *
  7. * This file is part of SingleFile.
  8. *
  9. * The code in this file is free software: you can redistribute it and/or
  10. * modify it under the terms of the GNU Affero General Public License
  11. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  12. * of the License, or (at your option) any later version.
  13. *
  14. * The code in this file is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  17. * General Public License for more details.
  18. *
  19. * As additional permission under GNU AGPL version 3 section 7, you may
  20. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  21. * AGPL normally required by section 4, provided you include this license
  22. * notice and a URL through which recipients can access the Corresponding
  23. * Source.
  24. */
  25. /* global fetch, Blob, AbortController, FormData */
  26. const AUTHORIZATION_HEADER = "Authorization";
  27. const BEARER_PREFIX_AUTHORIZATION = "Bearer ";
  28. const ACCEPT_HEADER = "Accept";
  29. const CONTENT_TYPE = "multipart/form-data";
  30. export { RestFormApi };
  31. class RestFormApi {
  32. constructor(token, restApiUrl, fileFieldName, urlFieldName) {
  33. this.headers = new Map([
  34. [AUTHORIZATION_HEADER, BEARER_PREFIX_AUTHORIZATION + token],
  35. [ACCEPT_HEADER, CONTENT_TYPE]
  36. ]);
  37. this.restApiUrl = restApiUrl;
  38. this.fileFieldName = fileFieldName;
  39. this.urlFieldName = urlFieldName;
  40. }
  41. async upload(filename, content, url) {
  42. this.controller = new AbortController();
  43. const blob = content instanceof Blob ? content : new Blob([content], { type: "text/html" });
  44. let formData = new FormData();
  45. if (this.fileFieldName) {
  46. formData.append(this.fileFieldName, blob, filename);
  47. }
  48. if (this.urlFieldName) {
  49. formData.append(this.urlFieldName, url);
  50. }
  51. const response = await fetch(this.restApiUrl, {
  52. method: "POST",
  53. body: formData,
  54. headers: this.headers,
  55. signal: this.controller.signal
  56. });
  57. if ([200, 201].includes(response.status)) {
  58. return response.json();
  59. } else {
  60. throw new Error(await response.text());
  61. }
  62. }
  63. abort() {
  64. if (this.controller) {
  65. this.controller.abort();
  66. }
  67. }
  68. }