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.

httpUtils.ts 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import base64js from 'base64-js';
  2. import { timeoutPromise } from './timeoutPromise';
  3. /**
  4. * The number of milliseconds before deciding that we need retry a fetch request.
  5. *
  6. * @type {number}
  7. */
  8. const RETRY_TIMEOUT = 3000;
  9. /**
  10. * Wrapper around fetch GET requests to handle json-ifying the response
  11. * and logging errors.
  12. *
  13. * @param {string} url - The URL to perform a GET against.
  14. * @param {?boolean} retry - Whether the request will be retried after short timeout.
  15. * @param {?Object} options - The request options.
  16. * @returns {Promise<Object>} The response body, in JSON format, will be
  17. * through the Promise.
  18. */
  19. export function doGetJSON(url: string, retry?: boolean, options?: Object) {
  20. const fetchPromise = fetch(url, options)
  21. .then(response => {
  22. const jsonify = response.json();
  23. if (response.ok) {
  24. return jsonify;
  25. }
  26. return jsonify
  27. .then(result => Promise.reject(result));
  28. });
  29. if (retry) {
  30. return timeoutPromise(fetchPromise, RETRY_TIMEOUT)
  31. .catch(response => {
  32. if (response.status >= 400 && response.status < 500) {
  33. return Promise.reject(response);
  34. }
  35. return timeoutPromise(fetchPromise, RETRY_TIMEOUT);
  36. });
  37. }
  38. return fetchPromise;
  39. }
  40. /**
  41. * Encodes strings to Base64URL.
  42. *
  43. * @param {any} data - The byte array to encode.
  44. * @returns {string}
  45. */
  46. export const encodeToBase64URL = (data: string): string => base64js
  47. .fromByteArray(new window.TextEncoder().encode(data))
  48. .replace(/=/g, '')
  49. .replace(/\+/g, '-')
  50. .replace(/\//g, '_');
  51. /**
  52. * Decodes strings from Base64URL.
  53. *
  54. * @param {string} data - The byte array to decode.
  55. * @returns {string}
  56. */
  57. export const decodeFromBase64URL = (data: string): string => {
  58. let s = data;
  59. // Convert from Base64URL to Base64.
  60. if (s.length % 4 === 2) {
  61. s += '==';
  62. } else if (s.length % 4 === 3) {
  63. s += '=';
  64. }
  65. s = s.replace(/-/g, '+').replace(/_/g, '/');
  66. // Convert Base64 to a byte array.
  67. return new window.TextDecoder().decode(base64js.toByteArray(s));
  68. };