Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import firebase from 'firebase';
- export default class BackendAPI {
- /**
- * @param {string} path
- * @param {string} method
- * @param {object} body
- * @returns {Promise}
- */
- static request(path, method = 'GET', body = null) {
- const url = `${process.env.REACT_APP_BACKEND_API}${path}`;
- const headers = { 'Accept': 'application/json' };
- if (body) {
- headers['Content-Type'] = 'application/json; charset=utf-8';
- }
- const call = () => fetch(url, {
- method,
- headers,
- body: body ? JSON.stringify(body) : undefined
- }).then(response => {
- if (response.ok) {
- return response.json();
- }
- return response.json().then(err => {
- throw err;
- })
- });
- if (firebase.auth().currentUser) {
- return firebase.auth().currentUser.getIdToken(true)
- .then(token => {
- headers['Authorization'] = token;
- return call();
- });
- }
- return call();
- }
- /**
- * @param {string} path
- * @returns {Promise}
- */
- static get(path) {
- return this.request(path);
- }
- /**
- * @param {string} path
- * @param {object} body
- * @returns {Promise}
- */
- static post(path, body = {}) {
- return this.request(path, 'POST', body)
- }
- /** USERS **/
- /**
- * Create a user
- *
- * @typedef {object} createUser
- * @typedef {string} createUser.firstName
- * @typedef {string} createUser.lastName
- * @typedef {string} createUser.phoneNumber
- * @typedef {string} createUser.email
- * @typedef {string} createUser.password
- *
- * @param {createUser}
- * @returns {Promise}
- */
- static createUser({
- firstName, lastName, phoneNumber, email, password
- }) {
- return this.post('/users', {
- firstName, lastName, phoneNumber, email, password
- });
- }
- /**
- * Get a user (own by default)
- *
- * @param {string} userId
- * @returns {Promise}
- */
- static getUser(userId = firebase.auth().currentUser.uid) {
- return this.get(`/users/${userId}`);
- }
- /**
- * Get a list of all users
- *
- * @returns {Promise}
- */
- static getAllUsers() {
- return this.get('/users');
- }
- /**
- * Toggle a user's admin role
- *
- * @param {string} userId
- * @returns {Promise}
- */
- static toggleAdmin(userId) {
- return this.post(`/users/${userId}/toggle-admin`);
- }
- }
Add Comment
Please, Sign In to add comment