IF YOU WOULD LIKE TO GET AN ACCOUNT, please write an email to s dot adaszewski at gmail dot com. User accounts are meant only to report issues and/or generate pull requests. This is a purpose-specific Git hosting for ADARED projects. Thank you for your understanding!
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.

68 lines
1.9KB

  1. //
  2. // Copyright (C) Stanislaw Adaszewski, 2020
  3. // Contact: s.adaszewski@gmail.com
  4. // Website: https://adared.ch/wba
  5. // License: GNU Affero General Public License, Version 3
  6. //
  7. import wbApplyPromiseOrdering from 'wb-apply-promise-ordering';
  8. const requestPromiseOrdering = {};
  9. function makeArvadosRequest(arvHost, arvToken, endpoint, params={}) {
  10. const defaultParams = {
  11. 'method': 'GET',
  12. 'data': null,
  13. 'contentType': 'application/json;charset=utf-8',
  14. 'responseType': 'json',
  15. 'useSsl': true,
  16. 'requireToken': true,
  17. 'onProgress': () => {},
  18. 'promiseOrdering': true,
  19. 'expectedStatus': 200
  20. };
  21. Object.keys(defaultParams).map(k => (params[k] =
  22. (k in params ? params[k] : defaultParams[k])));
  23. let { method, data, contentType, responseType,
  24. useSsl, requireToken, onProgress, promiseOrdering,
  25. expectedStatus } = params;
  26. if (!(arvHost && (arvToken || !requireToken)))
  27. return new Promise((accept, reject) => reject());
  28. let xhr = new XMLHttpRequest();
  29. xhr.open(method, (useSsl ? 'https://' : 'http://') + arvHost + endpoint);
  30. if (arvToken)
  31. xhr.setRequestHeader('Authorization', 'OAuth2 ' + arvToken);
  32. if (data !== null)
  33. xhr.setRequestHeader('Content-Type', contentType);
  34. xhr.responseType = responseType;
  35. xhr.onprogress = onProgress;
  36. let prom = new Promise((accept, reject) => {
  37. xhr.onreadystatechange = () => {
  38. if (xhr.readyState !== 4)
  39. return;
  40. if ((expectedStatus instanceof Array) &&
  41. expectedStatus.indexOf(xhr.status) !== -1) {
  42. accept(xhr);
  43. } else if (expectedStatus === xhr.status) {
  44. accept(xhr);
  45. } else {
  46. reject(xhr);
  47. }
  48. };
  49. xhr.send(data);
  50. });
  51. if (promiseOrdering)
  52. prom = wbApplyPromiseOrdering(prom, requestPromiseOrdering);
  53. return prom;
  54. }
  55. export default makeArvadosRequest;