request_builder.js 1015 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. class RequestBuilder {
  2. constructor(url) {
  3. this.callback = null;
  4. this.url = url;
  5. this.options = {
  6. method: "POST",
  7. cache: "no-cache",
  8. credentials: "include",
  9. body: null,
  10. headers: new Headers({
  11. "Content-Type": "application/json",
  12. "X-Csrf-Token": this.getCsrfToken()
  13. })
  14. };
  15. }
  16. withBody(body) {
  17. this.options.body = JSON.stringify(body);
  18. return this;
  19. }
  20. withCallback(callback) {
  21. this.callback = callback;
  22. return this;
  23. }
  24. getCsrfToken() {
  25. let element = document.querySelector("meta[name=X-CSRF-Token]");
  26. if (element !== null) {
  27. return element.getAttribute("value");
  28. }
  29. return "";
  30. }
  31. execute() {
  32. fetch(new Request(this.url, this.options)).then((response) => {
  33. if (this.callback) {
  34. this.callback(response);
  35. }
  36. });
  37. }
  38. }