ApiCaller.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /*
  2. Copyright (C) 2017 Cloudbase Solutions SRL
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /* eslint-disable */
  15. import React from 'react';
  16. import NotificationActions from '../../actions/NotificationActions';
  17. import Location from '../../core/Location';
  18. let apiInstance = null
  19. class ApiCaller {
  20. defaultHeaders = {
  21. "Content-Type": "application/json"
  22. }
  23. constructor() {
  24. if(!apiInstance){
  25. apiInstance = this;
  26. }
  27. return apiInstance;
  28. }
  29. sendAjaxRequest(options) {
  30. return new Promise((resolve, reject) => {
  31. let request = new XMLHttpRequest();
  32. //request.withCredentials = true
  33. request.open(options.method, options.url);
  34. let headers = Object.assign({}, this.defaultHeaders)
  35. if (options.headers) {
  36. for (let key in options.headers) {
  37. headers[key] = options.headers[key]
  38. }
  39. }
  40. for (let name in headers) {
  41. request.setRequestHeader(name, headers[name])
  42. }
  43. request.onreadystatechange = () => {
  44. if (request.readyState === 4) { //if complete
  45. if (!(request.status >= 200 && request.status <= 299)) { //check if "OK" (200)
  46. reject({ status: request.status });
  47. }
  48. }
  49. }
  50. console.log(`Sending ${options.method} Request to ${options.url}`);
  51. try {
  52. options.data ? request.send(JSON.stringify(options.data)) : request.send();
  53. }
  54. catch (err) {
  55. reject(err)
  56. }
  57. request.onload = () => {
  58. let result = {
  59. status: request.status,
  60. data: request.responseText ?
  61. (options.json !== false ? JSON.parse(request.responseText) : request.responseText): null,
  62. headers: ApiCaller.processHeaders(request.getAllResponseHeaders())
  63. };
  64. if (result.status >= 200 && result.status <= 299) {
  65. console.log(`Response ${options.url}`, result.data)
  66. resolve(result);
  67. } else {
  68. console.log(`Error Response: ${options.url}`, result.data);
  69. if (result.data && result.data.error && result.data.error.message) {
  70. NotificationActions.notify(result.data.error.message, "error")
  71. }
  72. if (result.status == 401) {
  73. this.resetHeaders()
  74. Location.push("/login")
  75. }
  76. reject({ status: request.status });
  77. }
  78. };
  79. request.onerror = () => {
  80. console.log('Error Response: ', result.data);
  81. reject({ status: 500, data: 'Connection error' });
  82. }
  83. });
  84. }
  85. resetHeaders() {
  86. this.defaultHeaders = {
  87. "Content-Type": "application/json"
  88. }
  89. }
  90. static processHeaders(rawHeaders) {
  91. let headers = {}
  92. let lines = rawHeaders.split("\n");
  93. lines.forEach(line => {
  94. let comps = line.split(':')
  95. if (comps[0].length) {
  96. headers[comps[0]] = comps[1].trim()
  97. }
  98. })
  99. return headers
  100. }
  101. setDefaultHeader(name, value) {
  102. if (value == null) {
  103. delete this.defaultHeaders[name]
  104. } else {
  105. this.defaultHeaders[name] = value
  106. }
  107. }
  108. }
  109. export default new ApiCaller;