/**
* @module method/get
*/
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 a user’s user meta from Firebase
*
* @param {object} user - User object
* @param {string} user.uid - Firebase User ID, e.g. hk_wx5555556.
*
* @return {userMeta} User’s user meta.
*/
const get = (user) => {
// check if user exists
return admin.auth().getUser(user.uid).then((result) => {
// look for user meta document
return db.collection('appUserMeta').doc(result.uid).get();
}).then((doc) => {
if (!doc.exists) {
throw new functions.https.HttpsError(
'not-found',
'User meta document cannot be found.',
'There is no existing user meta record corresponding to the provided identifier.'
);
}
const userMeta = doc.data();
userMeta['uid'] = doc.id;
console.info('[Success] Fetched user meta');
return userMeta;
}).catch((error) => {
// Assign error response to response
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.'
};
// Check if an HttpError has been thrown
if (has(error, 'code')) {
// Assign response
response = error;
}
// Check if an cloud function error has been thrown
if (has(error, 'errorInfo.code')) {
if (has(errorMessages, error.errorInfo.code)) {
response = errorMessages[error.errorInfo.code];
}
}
console.error('[Failure] Error fetching user meta:', error);
throw new functions.https.HttpsError(
response.code,
response.message,
response.details
);
});
};
module.exports = get;