The main server, and probably only repository in this org.
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.

92 lines
1.8 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. const PREFIX = "/api";
  2. function formatUrl(url, params = {}) {
  3. const urlWithPrefix = PREFIX + url;
  4. const queryString =
  5. Object
  6. .keys(params)
  7. .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]));
  8. if (queryString.length > 0) {
  9. return urlWithPrefix + "?" + queryString;
  10. }
  11. return urlWithPrefix;
  12. }
  13. /**
  14. * @param {Response} res
  15. * @return {Promise<array<object, object>>}
  16. */
  17. function authCheck(res) {
  18. return res.json().then(json => {
  19. if (typeof json.data === "undefined") {
  20. json.data = null;
  21. }
  22. if (typeof json.error === "undefined") {
  23. json.error = null;
  24. }
  25. return Promise.resolve(json);
  26. })
  27. }
  28. /**
  29. * @param {string} url
  30. * @param {object} params
  31. * @returns {Promise<object|null>}
  32. */
  33. export function fetchGet(url, params = {}) {
  34. return fetch(formatUrl(url, params), {
  35. method: "GET",
  36. credentials: "include",
  37. }).then(authCheck);
  38. }
  39. /**
  40. * @param {string} url
  41. * @param {object} params
  42. * @returns {Promise<object|null>}
  43. */
  44. export function fetchDelete(url, params = {}) {
  45. return fetch(formatUrl(url, params), {
  46. method: "DELETE",
  47. credentials: "include",
  48. }).then(authCheck);
  49. }
  50. /**
  51. * @param {string} url
  52. * @param {object} data
  53. * @returns {Promise<object|null>}
  54. */
  55. export function fetchPost(url, data = {}) {
  56. return fetch(formatUrl(url), {
  57. method: "POST",
  58. credentials: "include",
  59. headers: {
  60. "Content-Type": "application/json; charset=utf-8",
  61. },
  62. body: JSON.stringify(data),
  63. }).then(authCheck);
  64. }
  65. /**
  66. * @param {string} url
  67. * @param {object} data
  68. * @returns {Promise<object|null>}
  69. */
  70. export function fetchPatch(url, data = {}) {
  71. return fetch(formatUrl(url), {
  72. method: "PATCH",
  73. credentials: "include",
  74. headers: {
  75. "Content-Type": "application/json; charset=utf-8",
  76. },
  77. body: JSON.stringify(data),
  78. }).then(authCheck);
  79. }