method/getUserToken.js

/**
 * @module method/editBooking
 *
 * @requires method/getUserToken
 */

const functions = require('firebase-functions');
const axios = require('axios');
const {simplybook} = functions.config();

const {has} = require('lodash');

/**
 * Get an authentication token string to connect with SimplyBook
 *
 * @return {string} An authentication token for a certain registered user
 */
const getUserToken = () => {
  return axios({
    method: 'post',
    url: `${simplybook.url}/login`,
    data: {
      method: 'getUserToken',
      params: [simplybook.company, simplybook.username, simplybook.password],
      id: 0,
    }
  }).then(({data}) => {
    // Handle error
    if (has(data, 'error')) {
      throw new Error(data.error.message);
    }

    // Return token
    return data.result;
  }).catch((error) => {
    throw new functions.https.HttpsError(
      'permission-denied',
      error.message,
    );
  });
};

module.exports = getUserToken;