You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

request.ts 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2018 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. import { stringify } from 'querystring';
  21. import { omitBy, isNil } from 'lodash';
  22. import { getCookie } from './cookies';
  23. import { translate } from './l10n';
  24. /** Current application version. Can be changed if a newer version is deployed. */
  25. let currentApplicationVersion: string | undefined;
  26. export function getCSRFTokenName(): string {
  27. return 'X-XSRF-TOKEN';
  28. }
  29. export function getCSRFTokenValue(): string {
  30. const cookieName = 'XSRF-TOKEN';
  31. const cookieValue = getCookie(cookieName);
  32. if (!cookieValue) {
  33. return '';
  34. }
  35. return cookieValue;
  36. }
  37. /**
  38. * Return an object containing a special http request header used to prevent CSRF attacks.
  39. */
  40. export function getCSRFToken(): { [x: string]: string } {
  41. // Fetch API in Edge doesn't work with empty header,
  42. // so we ensure non-empty value
  43. const value = getCSRFTokenValue();
  44. return value ? { [getCSRFTokenName()]: value } : {};
  45. }
  46. export interface RequestData {
  47. [x: string]: any;
  48. }
  49. export function omitNil(obj: RequestData): RequestData {
  50. return omitBy(obj, isNil);
  51. }
  52. /**
  53. * Default options for any request
  54. */
  55. const DEFAULT_OPTIONS: {
  56. credentials: RequestCredentials;
  57. method: string;
  58. } = {
  59. credentials: 'same-origin',
  60. method: 'GET'
  61. };
  62. /**
  63. * Default request headers
  64. */
  65. const DEFAULT_HEADERS = {
  66. Accept: 'application/json'
  67. };
  68. /**
  69. * Request
  70. */
  71. class Request {
  72. private data?: RequestData;
  73. constructor(private url: string, private options: { method?: string } = {}) {}
  74. getSubmitData(customHeaders: any = {}): { url: string; options: RequestInit } {
  75. let { url } = this;
  76. const options: RequestInit = { ...DEFAULT_OPTIONS, ...this.options };
  77. if (this.data) {
  78. if (this.data instanceof FormData) {
  79. options.body = this.data;
  80. } else {
  81. const strData = stringify(omitNil(this.data));
  82. if (options.method === 'GET') {
  83. url += '?' + strData;
  84. } else {
  85. customHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
  86. options.body = strData;
  87. }
  88. }
  89. }
  90. options.headers = {
  91. ...DEFAULT_HEADERS,
  92. ...customHeaders
  93. };
  94. return { url, options };
  95. }
  96. submit(): Promise<Response> {
  97. const { url, options } = this.getSubmitData({ ...getCSRFToken() });
  98. return window.fetch((window as any).baseUrl + url, options);
  99. }
  100. setMethod(method: string): Request {
  101. this.options.method = method;
  102. return this;
  103. }
  104. setData(data?: RequestData): Request {
  105. if (data) {
  106. this.data = data;
  107. }
  108. return this;
  109. }
  110. }
  111. /**
  112. * Make a request
  113. */
  114. export function request(url: string): Request {
  115. return new Request(url);
  116. }
  117. /**
  118. * Make a cors request
  119. */
  120. export function corsRequest(url: string, mode: RequestMode = 'cors'): Request {
  121. const options: RequestInit = { mode };
  122. const request = new Request(url, options);
  123. request.submit = function() {
  124. const { url, options } = this.getSubmitData();
  125. return window.fetch(url, options);
  126. };
  127. return request;
  128. }
  129. function checkApplicationVersion(response: Response): boolean {
  130. const version = response.headers.get('Sonar-Version');
  131. if (version) {
  132. if (currentApplicationVersion && currentApplicationVersion !== version) {
  133. window.location.reload();
  134. return false;
  135. } else {
  136. currentApplicationVersion = version;
  137. }
  138. }
  139. return true;
  140. }
  141. /**
  142. * Check that response status is ok
  143. */
  144. export function checkStatus(response: Response): Promise<Response> {
  145. return new Promise((resolve, reject) => {
  146. if (checkApplicationVersion(response)) {
  147. if (response.status === 401) {
  148. import('../app/utils/handleRequiredAuthentication')
  149. .then(i => i.default())
  150. .then(reject, reject);
  151. } else if (response.status >= 200 && response.status < 300) {
  152. resolve(response);
  153. } else {
  154. reject({ response });
  155. }
  156. }
  157. });
  158. }
  159. /**
  160. * Parse response as JSON
  161. */
  162. export function parseJSON(response: Response): Promise<any> {
  163. return response.json();
  164. }
  165. /**
  166. * Parse response of failed request
  167. */
  168. export function parseError(error: { response: Response }): Promise<string> {
  169. const DEFAULT_MESSAGE = translate('default_error_message');
  170. try {
  171. return error.response
  172. .json()
  173. .then(r => r.errors.map((error: any) => error.msg).join('. '))
  174. .catch(() => DEFAULT_MESSAGE);
  175. } catch (ex) {
  176. return Promise.resolve(DEFAULT_MESSAGE);
  177. }
  178. }
  179. /**
  180. * Shortcut to do a GET request and return response json
  181. */
  182. export function getJSON(url: string, data?: RequestData): Promise<any> {
  183. return request(url)
  184. .setData(data)
  185. .submit()
  186. .then(checkStatus)
  187. .then(parseJSON);
  188. }
  189. /**
  190. * Shortcut to do a CORS GET request and return responsejson
  191. */
  192. export function getCorsJSON(url: string, data?: RequestData): Promise<any> {
  193. return corsRequest(url)
  194. .setData(data)
  195. .submit()
  196. .then(response => {
  197. if (response.status >= 200 && response.status < 300) {
  198. return Promise.resolve(response);
  199. } else {
  200. return Promise.reject({ response });
  201. }
  202. })
  203. .then(parseJSON);
  204. }
  205. /**
  206. * Shortcut to do a POST request and return response json
  207. */
  208. export function postJSON(url: string, data?: RequestData): Promise<any> {
  209. return request(url)
  210. .setMethod('POST')
  211. .setData(data)
  212. .submit()
  213. .then(checkStatus)
  214. .then(parseJSON);
  215. }
  216. /**
  217. * Shortcut to do a POST request
  218. */
  219. export function post(url: string, data?: RequestData): Promise<void> {
  220. return new Promise((resolve, reject) => {
  221. request(url)
  222. .setMethod('POST')
  223. .setData(data)
  224. .submit()
  225. .then(checkStatus)
  226. .then(() => {
  227. resolve();
  228. }, reject);
  229. });
  230. }
  231. /**
  232. * Shortcut to do a DELETE request and return response json
  233. */
  234. export function requestDelete(url: string, data?: RequestData): Promise<any> {
  235. return request(url)
  236. .setMethod('DELETE')
  237. .setData(data)
  238. .submit()
  239. .then(checkStatus);
  240. }
  241. /**
  242. * Delay promise for testing purposes
  243. */
  244. export function delay(response: any): Promise<any> {
  245. return new Promise(resolve => setTimeout(() => resolve(response), 1200));
  246. }
  247. export function requestTryAndRepeat<T>(
  248. repeatAPICall: () => Promise<T>,
  249. tries: number,
  250. slowTriesThreshold: number,
  251. repeatErrors = [404]
  252. ) {
  253. return repeatAPICall().catch((error: { response: Response }) => {
  254. if (repeatErrors.includes(error.response.status)) {
  255. tries--;
  256. if (tries > 0) {
  257. return new Promise(resolve => {
  258. setTimeout(
  259. () =>
  260. resolve(requestTryAndRepeat(repeatAPICall, tries, slowTriesThreshold, repeatErrors)),
  261. tries > slowTriesThreshold ? 500 : 3000
  262. );
  263. });
  264. }
  265. return Promise.reject();
  266. }
  267. return Promise.reject(error);
  268. });
  269. }