request.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { login_manager } from "./login_manager.js";
  2. export class request {
  3. get settings() {
  4. return {
  5. "method": this.method,
  6. "headers": this.headers,
  7. "body": this.body
  8. };
  9. }
  10. get _apikey() {
  11. const manager = new login_manager();
  12. if (manager.logged_in) {
  13. return manager.apikey;
  14. }
  15. throw new Error("User must be logged in.");
  16. }
  17. get method() {
  18. throw new TypeError("It must be overwrite.");
  19. }
  20. get url() {
  21. throw new TypeError("It must be overwrite.");
  22. }
  23. get headers() {
  24. if (this.method === "GET") {
  25. return {};
  26. }
  27. return {
  28. "Content-Type": "application/json"
  29. };
  30. }
  31. get body() {
  32. if (this.data === null) {
  33. return "";
  34. }
  35. return JSON.stringify(this.data);
  36. }
  37. get _response() {
  38. throw new TypeError("It must be overwrite.");
  39. }
  40. async connect() {
  41. const request = await fetch(this.url, this.settings);
  42. if (!request.ok) {
  43. throw new Error("Fail when requested: \"" + this.url + "\".");
  44. }
  45. const response = await request.json();
  46. if (!("result" in response)) {
  47. throw new Error("Bad response, not contain result.");
  48. }
  49. return new this._response(response);
  50. }
  51. get data() {
  52. throw new TypeError("This must be overwrite.");
  53. }
  54. }