Guest User

Untitled

a guest
Nov 15th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import firebase from 'firebase';
  2.  
  3. export default class BackendAPI {
  4.  
  5. /**
  6. * @param {string} path
  7. * @param {string} method
  8. * @param {object} body
  9. * @returns {Promise}
  10. */
  11. static request(path, method = 'GET', body = null) {
  12. const url = `${process.env.REACT_APP_BACKEND_API}${path}`;
  13. const headers = { 'Accept': 'application/json' };
  14.  
  15. if (body) {
  16. headers['Content-Type'] = 'application/json; charset=utf-8';
  17. }
  18.  
  19. const call = () => fetch(url, {
  20. method,
  21. headers,
  22. body: body ? JSON.stringify(body) : undefined
  23. }).then(response => {
  24. if (response.ok) {
  25. return response.json();
  26. }
  27.  
  28. return response.json().then(err => {
  29. throw err;
  30. })
  31. });
  32.  
  33. if (firebase.auth().currentUser) {
  34. return firebase.auth().currentUser.getIdToken(true)
  35. .then(token => {
  36. headers['Authorization'] = token;
  37. return call();
  38. });
  39. }
  40.  
  41. return call();
  42. }
  43.  
  44. /**
  45. * @param {string} path
  46. * @returns {Promise}
  47. */
  48. static get(path) {
  49. return this.request(path);
  50. }
  51.  
  52. /**
  53. * @param {string} path
  54. * @param {object} body
  55. * @returns {Promise}
  56. */
  57. static post(path, body = {}) {
  58. return this.request(path, 'POST', body)
  59. }
  60.  
  61. /** USERS **/
  62.  
  63. /**
  64. * Create a user
  65. *
  66. * @typedef {object} createUser
  67. * @typedef {string} createUser.firstName
  68. * @typedef {string} createUser.lastName
  69. * @typedef {string} createUser.phoneNumber
  70. * @typedef {string} createUser.email
  71. * @typedef {string} createUser.password
  72. *
  73. * @param {createUser}
  74. * @returns {Promise}
  75. */
  76. static createUser({
  77. firstName, lastName, phoneNumber, email, password
  78. }) {
  79. return this.post('/users', {
  80. firstName, lastName, phoneNumber, email, password
  81. });
  82. }
  83.  
  84. /**
  85. * Get a user (own by default)
  86. *
  87. * @param {string} userId
  88. * @returns {Promise}
  89. */
  90. static getUser(userId = firebase.auth().currentUser.uid) {
  91. return this.get(`/users/${userId}`);
  92. }
  93.  
  94. /**
  95. * Get a list of all users
  96. *
  97. * @returns {Promise}
  98. */
  99. static getAllUsers() {
  100. return this.get('/users');
  101. }
  102.  
  103. /**
  104. * Toggle a user's admin role
  105. *
  106. * @param {string} userId
  107. * @returns {Promise}
  108. */
  109. static toggleAdmin(userId) {
  110. return this.post(`/users/${userId}/toggle-admin`);
  111. }
  112.  
  113. }
Add Comment
Please, Sign In to add comment