user/amd/src/repository.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * Module to handle AJAX interactions.
  17. *
  18. * @module core_user/repository
  19. * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. import Config from 'core/config';
  23. import {call as fetchMany} from 'core/ajax';
  24. import Fetch from 'core/fetch';
  25. const checkUserId = (userid) => {
  26. if (Number(userid) === 0) {
  27. return;
  28. }
  29. if (Number(userid) === Config.userId) {
  30. return;
  31. }
  32. throw new Error(
  33. `Invalid user ID: ${userid}. It is only possible to manage preferences for the current user.`,
  34. );
  35. };
  36. /**
  37. * Turn the response object into a Proxy object that will log a warning if the saved property is accessed.
  38. *
  39. * @param {Object} response
  40. * @param {Object} preferences The preferences that might be in the response
  41. * @return {Promise<Proxy>}
  42. */
  43. const addLegacySavedProperty = (response, preferences) => {
  44. const debugLogger = {
  45. get(target, prop, receiver) {
  46. if (prop === 'then') {
  47. // To proxy a Promise we have to return null when the then key is requested.
  48. return null;
  49. }
  50. if (prop === 'saved') {
  51. window.console.warn(
  52. 'The saved property is deprecated. Please use the response object directly.',
  53. );
  54. return preferences
  55. .filter((preference) => target.hasOwnProperty(preference.name))
  56. .map((preference) => ({
  57. name: preference.name,
  58. userid: Config.userid,
  59. }));
  60. }
  61. return Reflect.get(target, prop, receiver);
  62. },
  63. };
  64. return Promise.resolve(new Proxy(response, debugLogger));
  65. };
  66. /**
  67. * Get single user preference
  68. *
  69. * @param {String} name Name of the preference
  70. * @param {Number} userid User ID (defaults to current user)
  71. * @return {Promise}
  72. */
  73. export const getUserPreference = (name, userid = 0) => getUserPreferences(name, userid)
  74. .then((response) => response[name]);
  75. /**
  76. * Get multiple user preferences
  77. *
  78. * @param {String|null} name Name of the preference (omit if you want to retrieve all)
  79. * @param {Number} userid User ID (defaults to current user)
  80. * @return {Promise<object<string, string>>}
  81. */
  82. export const getUserPreferences = (name = null, userid = 0) => {
  83. checkUserId(userid);
  84. const endpoint = ['current', 'preferences'];
  85. if (name) {
  86. endpoint.push(name);
  87. }
  88. return Fetch.performGet('core_user', endpoint.join('/')).then((response) => response.json());
  89. };
  90. /**
  91. * Set single user preference
  92. *
  93. * @param {String} name Name of the preference
  94. * @param {String|null} value Value of the preference (omit if you want to remove the current value)
  95. * @param {Number} userid User ID (defaults to current user)
  96. * @return {Promise}
  97. */
  98. export const setUserPreference = (name, value = null, userid = 0) => {
  99. checkUserId(userid);
  100. return Fetch.performPost(
  101. 'core_user',
  102. `current/preferences/${name}`,
  103. {
  104. body: {value},
  105. },
  106. )
  107. // Return the result of the fetch call, and also add in the legacy saved property.
  108. .then((response) => response.json())
  109. .then((response) => addLegacySavedProperty(response, [{name}]));
  110. };
  111. /**
  112. * Set multiple user preferences
  113. *
  114. * @param {Object[]} preferences Array of preferences containing name/value/userid attributes
  115. * @return {Promise}
  116. */
  117. export const setUserPreferences = (preferences) => {
  118. preferences.forEach((preference) => checkUserId(preference.userid));
  119. return Fetch.performPost(
  120. 'core_user',
  121. 'current/preferences',
  122. {
  123. body: {
  124. preferences: Object.fromEntries (preferences.map((preference) => ([preference.name, preference.value]))),
  125. },
  126. },
  127. )
  128. // Return the result of the fetch call, and also add in the legacy saved property.
  129. .then((response) => response.json())
  130. .then((response) => addLegacySavedProperty(response, preferences));
  131. };
  132. /**
  133. * Unenrol the user with the specified user enrolmentid ID.
  134. *
  135. * @param {Number} userEnrolmentId
  136. * @return {Promise}
  137. */
  138. export const unenrolUser = userEnrolmentId => {
  139. return fetchMany([{
  140. methodname: 'core_enrol_unenrol_user_enrolment',
  141. args: {
  142. ueid: userEnrolmentId,
  143. },
  144. }])[0];
  145. };
  146. /**
  147. * Submit the user enrolment form with the specified form data.
  148. *
  149. * @param {String} formdata
  150. * @return {Promise}
  151. */
  152. export const submitUserEnrolmentForm = formdata => {
  153. return fetchMany([{
  154. methodname: 'core_enrol_submit_user_enrolment_form',
  155. args: {
  156. formdata,
  157. },
  158. }])[0];
  159. };
  160. export const createNotesForUsers = notes => {
  161. return fetchMany([{
  162. methodname: 'core_notes_create_notes',
  163. args: {
  164. notes
  165. }
  166. }])[0];
  167. };
  168. export const sendMessagesToUsers = messages => {
  169. return fetchMany([{
  170. methodname: 'core_message_send_instant_messages',
  171. args: {messages}
  172. }])[0];
  173. };