api.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  3. * SPDX-License-Identifier: AGPL-3.0-or-later
  4. */
  5. import axios from '@nextcloud/axios'
  6. import { confirmPassword } from '@nextcloud/password-confirmation'
  7. import '@nextcloud/password-confirmation/dist/style.css'
  8. const sanitize = function(url) {
  9. return url.replace(/\/$/, '') // Remove last url slash
  10. }
  11. export default {
  12. /**
  13. * This Promise is used to chain a request that require an admin password confirmation
  14. * Since chaining Promise have a very precise behavior concerning catch and then,
  15. * you'll need to be careful when using it.
  16. * e.g
  17. * // store
  18. * action(context) {
  19. * return api.requireAdmin().then((response) => {
  20. * return api.get('url')
  21. * .then((response) => {API success})
  22. * .catch((error) => {API failure});
  23. * }).catch((error) => {requireAdmin failure});
  24. * }
  25. * // vue
  26. * this.$store.dispatch('action').then(() => {always executed})
  27. *
  28. * Since Promise.then().catch().then() will always execute the last then
  29. * this.$store.dispatch('action').then will always be executed
  30. *
  31. * If you want requireAdmin failure to also catch the API request failure
  32. * you will need to throw a new error in the api.get.catch()
  33. *
  34. * e.g
  35. * api.requireAdmin().then((response) => {
  36. * api.get('url')
  37. * .then((response) => {API success})
  38. * .catch((error) => {throw error;});
  39. * }).catch((error) => {requireAdmin OR API failure});
  40. *
  41. * @return {Promise}
  42. */
  43. requireAdmin() {
  44. return confirmPassword()
  45. },
  46. get(url, options) {
  47. return axios.get(sanitize(url), options)
  48. },
  49. post(url, data) {
  50. return axios.post(sanitize(url), data)
  51. },
  52. patch(url, data) {
  53. return axios.patch(sanitize(url), data)
  54. },
  55. put(url, data) {
  56. return axios.put(sanitize(url), data)
  57. },
  58. delete(url, data) {
  59. return axios.delete(sanitize(url), { params: data })
  60. },
  61. }