method/getVersionCode.js

/**
 * @module method/getVersionCode
 */

const admin = require('firebase-admin');
const functions = require('firebase-functions');

const db = admin.firestore();

const {has} = require('lodash');
const errorMessages = require('../error/error.json');

/**
 * Get minimum application version code from Firebase
 *
 * @return {number} App version code.
 */
const getVersionCode = () => {
  // check if user exists
  return db.collection('appGlobalSettings').doc('minimumVersion').get().then((doc) => {
    if (!doc.exists) {
      throw new Error('Minimum version document cannot be found');
    }

    const {versionCode} = doc.data();

    console.info('[Success] Fetched minimum version code');

    return versionCode;
  }).catch((error) => {
    let response = {
      "code": "unknown",
      "message": "Sorry, there are some issues on our side",
      "details": "Please try again in a few minutes. If it’s still not working, call us at +852 9847 4943."
    };

    console.error('[Failure] Error fetching minimum version code:', error);

    if (has(error, 'errorInfo.code')) {
      if (has(errorMessages, error.errorInfo.code)) {
        response = errorMessages[error.errorInfo.code];
      }
    }

    throw new functions.https.HttpsError(
        response.code,
        response.message,
        response.details
    );
  });
};

module.exports = getVersionCode;