Firebase Cloud Function updating ref with incorrect values - javascript

I want to add a new node to the database if the node doesn't exist. I don't want to return anything to the client, I just want to update the database with the new values. On the client I have a listener that observes the credit_counts property, once the update happens it receives it there and notifies all users that this particular user has a new credit.
In the code below I check to see if (!snapshot.exists() and if it's not there I add the node to the database using admin.database().ref('/user_credits/{creditId}/{userId}').set({ dict });. After pasting the url I check the db and the layout is:
I'm a Swift developer. In Swift I can just do:
Database.database().reference().child("/user_credits/\(creditId)/\(userId)").setValue(dict) and the tree will be correct.
user_credits > {creditId} > {userId} > dict are incorrect. It should be user_credits > sample_123 > user_xyz > dict values. Where am I going wrong at?
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";
admin.database().ref('user_credits').child(creditId).child(userId).once('value', snapshot => {
if (!snapshot.exists()) {
var dict = {
"joined_date": receivedTimeStamp,
"timeStamp": receivedTimeStamp,
"credits_count": 1
};
return admin.database().ref('/user_credits/{creditId}/{userId}').set({ dict });
} else {
const previousTimeStamp = snapshot.child("timeStamp").val();
const creditsCount = snapshot.child("credits_count").val();
if (previousTimeStamp + whatever) < currentTimeStamp {
let updatedCount = creditsCount + 1
return admin.database().ref('/user_credits/{creditId}/{userId}').update({ "timeStamp": receivedTimeStamp, "credits_count": updatedCount });
} else {
return true
}
}
});
});

I had to change the ref to:
return admin.database().ref('/user_credits/' + creditId + '/' + userId).set({ "joined_date": receivedTimeStamp, "timeStamp": receivedTimeStamp, "credits_count": 1 });
I also had to update the ref inside the else statement to follow the same format.

The syntax is fine, but the reference does not match the structure; that should rather be:
admin.database().ref('user_credits').child(creditId).child(userId).child('dict')
... else there won't be any snapshot.child("timeStamp") or snapshot.child("credits_count").

Related

Execute promise or await with generated string variable

I am building a mongoose query and storing it in a variable call query. The code below shows it
let query = "Product.find(match)";
if (requestObject.query.sortBy) {
query = query.concat(".", "sort(sort)");
const parts = requestObject.query.sortBy.split(":");
sort[parts[0]] = parts[1] === "desc" ? -1 : 1;
}
if (requestObject.query.fields) {
query = query.concat(".", "select(fields)");
const fields = requestObject.query.fields.split(",").join(" ");
const items = await Product.find(match).sort(sort).select(fields); //.populate("category").exec();
/**const items = await Product.find(match).sort(sort).select("-__v"); //.populate("category").exec();**/
}
I am facing an issue when attempting to run a mongoose query that I have generated and stored in a string. When I run it in post man, the response is 200 but no data is returned. Below is a console.log(query) on line 2
what I hope to achieve is to have await or create a new promise execute the content id query variable like shown below
const items = new Promise((resolve) => resolve(query)); //.populate("category").exec();
items
? responseObject.status(200).json(items)
: responseObject
.status(400)
.json({ message: "Could not find products, please try again" });
I will appreciate it very much that and also if you can give me a better way of doing it, I will love that
This doesn't really make sense. You are building a string, not a query. You can't do anything with that string. (You could eval it, but you really shouldn't). Instead, build a query object!
let query = Product.find(match);
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {};
sort[field] = dir === "desc" ? -1 : 1;
query = query.sort(sort);
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
}
//query.populate("category")
const items = await query.exec();
if (items) {
responseObject.status(200).json(items)
} else {
responseObject.status(400).json({ message: "Could not find products, please try again" });
}
If you really want to get that string for something (e.g. debugging), build it separately from the query:
let query = Product.find(match);
let queryStr = 'Product.find(match)';
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {[field]: dir === "desc" ? -1 : 1};
query = query.sort(sort);
queryStr += `.sort(${JSON.stringify(sort)})`;
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
queryStr += `.select(${JSON.stringify(fields)})`;
}
//query.populate("category")
//queryStr += `.populate("category")`;
console.log(queryStr);
const items = await query.exec();
…

Wait for all Firebase data query requests before executing code

I am trying to fetch data from different collections in my cloud Firestore database in advance before I process them and apply them to batch, I created two async functions, one to capture the data and another to execute certain code only after all data is collected, I didn't want the code executing and creating errors before the data is fetched when i try to access the matchesObject after the async function to collect data is finished, it keeps saying "it cannot access a property matchStatus of undefined", i thought took care of that with async and await? could anyone shed some light as to why it is undefined one moment
axios.request(options).then(function(response) {
console.log('Total matches count :' + response.data.matches.length);
const data = response.data;
var matchesSnapshot;
var marketsSnapshot;
var tradesSnapshot;
var betsSnapshot;
matchesObject = {};
marketsObject = {};
tradesObject = {};
betsObject = {};
start();
async function checkDatabase() {
matchesSnapshot = await db.collection('matches').get();
matchesSnapshot.forEach(doc => {
matchesObject[doc.id] = doc.data();
console.log('matches object: ' + doc.id.toString())
});
marketsSnapshot = await db.collection('markets').get();
marketsSnapshot.forEach(doc2 => {
marketsObject[doc2.id] = doc2.data();
console.log('markets object: ' + doc2.id.toString())
});
tradesSnapshot = await db.collection('trades').get();
tradesSnapshot.forEach(doc3 => {
tradesObject[doc3.id] = doc3.data();
console.log('trades object: ' + doc3.id.toString())
});
betsSnapshot = await db.collection('bets').get();
betsSnapshot.forEach(doc4 => {
betsObject[doc4.id] = doc4.data();
console.log('bets object: ' + doc4.id.toString())
});
}
async function start() {
await checkDatabase();
// this is the part which is undefined, it keeps saying it cant access property matchStatus of undefined
console.log('here is matches object ' + matchesObject['302283']['matchStatus']);
if (Object.keys(matchesObject).length != 0) {
for (let bets of Object.keys(betsObject)) {
if (matchesObject[betsObject[bets]['tradeMatchId']]['matchStatus'] == 'IN_PLAY' && betsObject[bets]['matched'] == false) {
var sfRef = db.collection('users').doc(betsObject[bets]['user']);
batch11.set(sfRef, {
accountBalance: admin.firestore.FieldValue + parseFloat(betsObject[bets]['stake']),
}, {
merge: true
});
var sfRef = db.collection('bets').doc(bets);
batch12.set(sfRef, {
tradeCancelled: true,
}, {
merge: true
});
}
}
}
});
There are too many smaller issues in the current code to try to debug them one-by-one, so this refactor introduces various tests against your data. It currently won't make any changes to your database and is meant to be a replacement for your start() function.
One of the main differences against your current code is that it doesn't unnecessarily download 4 collections worth of documents (two of them aren't even used in the code you've included).
Steps
First, it will get all the bet documents that have matched == false. From these documents, it will check if they have any syntax errors and report them to the console. For each valid bet document, the ID of it's linked match document will be grabbed so we can then fetch all the match documents we actually need. Then we queue up the changes to the user's balance and the bet's document. Finally we report about any changes to be done and commit them (once you uncomment the line).
Code
Note: fetchDocumentById() is defined in this gist. Its a helper function to allow someCollectionRef.where(FieldPath.documentId(), 'in', arrayOfIds) to take more than 10 IDs at once.
async function applyBalanceChanges() {
const betsCollectionRef = db.collection('bets');
const matchesCollectionRef = db.collection('matches');
const usersCollectionRef = db.collection('users');
const betDataMap = {}; // Record<string, BetData>
await betsCollectionRef
.where('matched', '==', false)
.get()
.then((betsSnapshot) => {
betsSnapshot.forEach(betDoc => {
betDataMap[betDoc.id] = betDoc.data();
});
});
const matchDataMap = {}; // Record<string, MatchData | undefined>
// betIdList contains all IDs that will be processed
const betIdList = Object.keys(betDataMap).filter(betId => {
const betData = betDataMap[betId];
if (!betData) {
console.log(`WARN: Skipped Bet #${betId} because it was falsy (actual value: ${betData})`);
return false;
}
const matchId = betData.tradeMatchId;
if (!matchId) {
console.log(`WARN: Skipped Bet #${betId} because it had a falsy match ID (actual value: ${matchId})`);
return false;
}
if (!betData.user) {
console.log(`WARN: Skipped Bet #${betId} because it had a falsy user ID (actual value: ${userId})`);
return false;
}
const stakeAsNumber = Number(betData.stake); // not using parseFloat as it's too lax
if (isNaN(stakeAsNumber)) {
console.log(`WARN: Skipped Bet #${betId} because it had an invalid stake value (original NaN value: ${betData.stake})`);
return false;
}
matchDataMap[matchId] = undefined; // using undefined because its the result of `doc.data()` when the document doesn't exist
return true;
});
await fetchDocumentsById(
matchesCollectionRef,
Object.keys(matchIdMap),
(matchDoc) => matchDataMap[matchDoc.id] = matchDoc.data()
);
const batch = db.batch();
const queuedUpdates = 0;
betIdList.forEach(betId => {
const betData = betDataMap[betId];
const matchData = matchDataMap[betData.tradeMatchId];
if (matchData === undefined) {
console.log(`WARN: Skipped /bets/${betId}, because it's linked match doesn't exist!`);
continue;
}
if (matchData.matchStatus !== 'IN_PLAY') {
console.log(`INFO: Skipped /bets/${betId}, because it's linked match status is not "IN_PLAY" (actual value: ${matchData.matchStatus})`);
continue;
}
const betRef = betsCollectionRef.doc(betId);
const betUserRef = usersCollectionRef.doc(betData.user);
batch.update(betUserRef, { accountBalance: admin.firestore.FieldValue.increment(Number(betData.stake)) });
batch.update(betRef, { tradeCancelled: true });
queuedUpdates += 2; // for logging
});
console.log(`INFO: Batch currently has ${queuedUpdates} queued`);
// only uncomment when you are ready to make changes
// batch.commit();
}
Usage:
axios.request(options)
.then(function(response) {
const data = response.data;
console.log('INFO: Total matches count from API:' + data.matches.length);
return applyBalanceChanges();
}

Why does it not detect DB changes(functions)?

So I'm learning firebase functions and I'm trying to have a function detect a change in the DB but it doesn't. Its suppose to be detect when the gamemode is changed though it doesn't do shit. if it does detect the change it changes it to gamemode 3 though as stated it does not do anything. This is done via firestore
my test DB: https://gyazo.com/91afd83cd27a0e7c55bd79b2b86529bf
Here is what i do to trigger it:
https://gyazo.com/8c7206d80a343b0e7ee9432cf3fae47c
and my node.js script is as follows:
exports.tellGameModeofUser = functions.firestore
.document('users/{userId}')
.onUpdate(event => {
// Retrieve the current and previous value
const data = event.data.data();
const previousData = event.data.previous.data();
// We'll only update if the name has changed.
// This is crucial to prevent infinite loops.
console.log("the new game mode: " + data );
console.log("old gmae mode: " + previousData)
if (data.gamemode === previousData.gamemode){
return;
}else if (data.gamemode === "1"){
console.log("value changed game mode on");
}
});
When I check the log is see nothing posted, there is no trigger.
The cloud functions have been updated, so you need to change to the following:
exports.tellGameModeofUser = functions.firestore
.document('users/{userId}')
.onUpdate(event => {
const data = event.data.data();
const previousData = event.data.previous.data();
to this:
exports.tellGameModeofUser = functions.firestore.document('users/{userId}').onUpdate((change,context) => {
const data = change.after.data();
const previousData = change.before.data();
});
more info here:
https://firebase.google.com/docs/functions/beta-v1-diff#cloud-firestore
So 1 I had to update the firebase to 1.0.0 and that had allowed me to use the new function syntax. Then I was able to use the new syntax for onUpdate functions and have the function run as needed.
exports.tellGameModeofUser = functions.firestore.document('Users/{userId}')
.onUpdate((change,context) => {
console.log("Hey");
console.log("change: " +change);
const beforeData = change.before.data() // data before the write
const afterData = change.after.data(); // data after the write
// We'll only update if the name has changed.
// This is crucial to prevent infinite loops.
console.log("the new game mode: " + afterData );
console.log("old gmae mode: " + beforeData)
if (afterData.gamemode === beforeData.gamemode){
console.log("game mode is the same");
return;
}else if (afterData.gamemode === "1"){
console.log("value changed game mode on");
}
});

Firebase - Toggling value with transactions

I'm trying to let users favorite a project. I'm storing these projects at 2 places so I have to update them simultaneously. After looking at the firebase docs, using transactions seemed to be the best option.
.
Function to toggle the favorite status:
function toggleFavorite (projectReference, uid) {
projectReference.transaction(function(project) {
console.log('Before-Favorites :' + project.favoriteCount);
if (project.favorites && project.favorites[uid]) {
project.favoriteCount--;
project.favorites[uid] = null;
} else {
project.favoriteCount++;
if(!project.favorites) {
project.favorites= {};
}
project.favorites[uid] = true;
}
console.log(' After-Favorites :' + project.favoriteCount);
return project;
});
};
Function to add the eventListeners to the projects:
function AddToFavorite (uid, authorId) {
const favoriteList = document.querySelectorAll('.btnFavorite');
for(var i = 0; i<favoriteList.length; i++) {
favoriteList[i].addEventListener('click', function(event) {
const projectId = this.dataset.id;
console.log(projectId);
const globalProjectRef = firebase.database().ref('/projects/' + projectId);
const userProjectRef = firebase.database().ref('/user-projects/' + authorId + '/' + projectId);
toggleFavorite(globalProjectRef,uid);
toggleFavorite(userProjectRef,uid);
});
}
}
I want to store the uid of the current user under a 'favorites' node within the project location.
When i want to store the data I can see it appearing in the database but removing it after instantly. Followed by that i get an error in the console that my project object is null.
What's the best way of solving this issue ?

Firebase multi-path updates just overwrites the supposed node

In the code below I am trying to use a cloud function to do a multiple update of setting some of my fields to a new value, but it just results to overwriting each of the nodes. I don't really understand this behavior, cos I just needed a simple update.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.onJobBid_Status = functions.database
.ref("/JobBids/{jobId}/{bidId}/status")
.onWrite((event) => {
let newStatus = event.data.val();
let updates = {};
updates["/Jobs/" + event.params.jobId] = { status: newStatus, };
updates["/Users/" + event.params.bidId + "/JobBids/" + event.params.jobId] = { status: newStatus, level:"4", color:"green" };
return admin.database().ref().update(updates);
});
When you call update, the Firebase server:
Loops through the properties/paths of the updates.
For each property/path, performs a set() operation.
So while you can update specific paths, at each path the operation is a regular set(). This means it replaces the data under each path.
The solution is to have the entire path to the lowest-level property in your key. So in your case:
let updates = {};
updates["/Jobs/" + event.params.jobId+"/status"] = newStatus;
let jobPath = "/Users/" + event.params.bidId + "/JobBids/" + event.params.jobId;
updates[jobPath+/status"] = newStatus;
updates[jobPath+/level"] = "4"; // consider storing this as a number
updates[jobPath+/color"] = "green" ;
With these updates, you will only replace the values of the status, level and color properties.

Categories

Resources