Fetcher.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 Hackware SpA <human@hackware.cl>
  2. // This file is part of "Hackware Userland" and licensed under the terms
  3. // of the GNU Affero General Public License version 3, or (at your option)
  4. // a later version. You should have received a copy of this license along
  5. // with the software. If not, see <https://www.gnu.org/licenses/>.
  6. export default class Fetcher {
  7. constructor(haweseEndpoint) {
  8. this.haweseEndpoint = haweseEndpoint;
  9. }
  10. haweseGet(path, queryParams = {}, headers = {}, processResponse = true) {
  11. const strQueryParams = Object.entries(queryParams).length
  12. ? `?${(new URLSearchParams(queryParams)).toString()}`
  13. : '';
  14. return fetch(`${this.haweseEndpoint}${path}${strQueryParams}`, {
  15. method: 'GET',
  16. mode: 'cors',
  17. credentials: 'include',
  18. headers,
  19. }).then(response => (processResponse ? Fetcher.haweseProcessResponse(response) : response));
  20. }
  21. hawesePost(path, bodyParams = {}, headers = {}, processResponse = true) {
  22. let jsonBodyParams;
  23. if (bodyParams instanceof HTMLFormElement) {
  24. jsonBodyParams = Fetcher.formToObject(bodyParams);
  25. } else {
  26. jsonBodyParams = bodyParams;
  27. }
  28. jsonBodyParams = JSON.stringify(jsonBodyParams);
  29. const localHeaders = {
  30. ...{ 'Content-Type': 'application/json' },
  31. ...headers,
  32. };
  33. return fetch(`${this.haweseEndpoint}${path}`, {
  34. method: 'POST',
  35. mode: 'cors',
  36. credentials: 'include',
  37. headers: localHeaders,
  38. body: jsonBodyParams,
  39. }).then(response => (processResponse ? Fetcher.haweseProcessResponse(response) : response));
  40. }
  41. static haweseProcessResponse(response) {
  42. if ([401, 403].includes(response.status)) {
  43. // I'd like to do something else here, but this class has to do with
  44. // fetching things, not handling authentication nor redirecting with
  45. // the router. So I'll just dump an error to the console.
  46. // Something like this is done in the router.js:beforeEach
  47. throw new Error(`${response.statusText} request to ${response.url}`);
  48. }
  49. return response.json();
  50. }
  51. // Return an object from a form element (such as event.target)
  52. static formToObject(formElement) {
  53. const object = {};
  54. (new FormData(formElement)).forEach((value, key) => {
  55. object[key] = value;
  56. });
  57. return object;
  58. }
  59. }