I need to nest some promises.
I first need to increment a ref using: .set(admin.database.ServerValue.increment(1))
Once that is done I need to update some data at a different ref: return admin.database().ref('/user_credits/' + creditId + '/' + userId).set({ "joined_date": receivedTimeStamp, "timeStamp": receivedTimeStamp, "credits_count": 1 })
The below code works and both refs update as expected but I get a warning of:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.updateViewsCtAtPostsRef = functions.https.onRequest((request, response) => {
const currentTimeStamp = Date.now();
const receivedTimeStamp = admin.database.ServerValue.TIMESTAMP;
const creditId = "sample_123";
const userId = "userId_xyz";
const gameId = "game_abc";
admin.database().ref('user_credits').child(creditId).child(userId).once('value', snapshot => {
if (!snapshot.exists()) {
admin.database().ref('/games/' + gameId + '/' + 'score').set(admin.database.ServerValue.increment(1))
.then(() => {
return admin.database().ref('/user_credits/' + creditId + '/' + userId).set({ "joined_date": receivedTimeStamp, "timeStamp": receivedTimeStamp, "credits_count": 1 })
.then(() => {
return true;
})
.catch(error);
})
.catch(error);
} else {
const previousTimeStamp = snapshot.child("timeStamp").val();
const creditsCount = snapshot.child("credits_count").val();
if (previousTimeStamp + whatever) < currentTimeStamp {
let updatedCount = creditsCount + 1;
admin.database().ref('/games/' + gameId + '/' + 'score').set(admin.database.ServerValue.increment(1))
.then(() => {
return admin.database().ref('/user_credits/' + creditId + '/' + userId).update({ "timeStamp": receivedTimeStamp, "credits_count": updatedCount })
.then(() => {
return true;
})
.catch(error);
})
.catch(error);
} else {
return true
}
}
});
});