Firebase won't add full entirety of object when using set() [duplicate] - javascript

This question already has answers here:
Create an empty child record in Firebase
(2 answers)
Closed 6 years ago.
I'm working on a chrome extension and pushing data from a Google-authenticated user to Firebase.
I'm listening for a message coming from another JS file and when it comes in, I want to take the "user profile" object (request) and tack on a property to it, called "visitedLinks". visitedLinks should be set to an empty object.
I do 3 console.logs throughout the code, and in all three cases, the console.logs show "visitedLinks" set to an empty object, yet when I push to Firebase, "visitedLinks" isn't a property.
//Relevant 3 console statements are the following
//console.log('request.accountData = ', request.accountData)
//console.log('userObject test #1 = ', userObject)
//console.log('userObject = ', userObject)
var rootRef = new Firebase("https://search-feed-35574.firebaseio.com/");
if (localStorage.userIsAuthenticated) {
console.log('user is authenticaled')
chrome.runtime.onMessage.addListener(
//listen for messages
function(request, sender, sendResponse) {
//url is coming in from a content script, use localStorage.uid to make database call
if (request.url) {
console.log('message coming from content script')
var uid = localStorage.uid;
var url = request.url;
var userRef = rootRef.child(uid);
newLinkRef = userRef.push(url);
//otherwise, we're getting a message from popup.js, meaning they clicked it again, or they've signed in for the first time
} else {
console.log('message coming from popup')
//here we're passing in all the data from the person's Google user account
var googleUID = request.accountData.uid
//then we make a new object with the key as their google UID and the value all the account data
request.accountData.visitedLinks = {}
console.log('request.accountData = ', request.accountData)
var userObject = {};
userObject[googleUID] = request.accountData;
console.log('userObject test #1 = ', userObject)
//here were checking to see if the UID is already a key in the database
//basically, if they've ever logged in
rootRef.once('value', function(snapshot) {
if (snapshot.hasChild(googleUID)) {
//user has authenticated before, they just happened to click the popup again
console.log('already authenticated, you just clicked the popup again')
} else {
console.log('users first DB entry');
//if they're not in the database yet, we need to push userObject to the DB
//and push their current url to the publicLinks array
rootRef.set(userObject, function(error) {
console.log('error = ', error);
console.log('userObject after DB insert = ', userObject)
});
}
})
}
//figure out if this user has entries in the DB already
//just push the link information onto the "links" node of the db object
//if not, push a ref (to the right place)
// console.log(sender)
});
} else {
console.log('user isnt authenticated')
}

So it turns out that you can't insert empty objects into the database. Similar question answered here: Create an empty child record in Firebase

Related

Dialogflow Firebase Realtime Database Getting Error: No responses defined for platform: Undefined yet method still goes through

I've been trying for a project I'm working on to develop a function for a Food chatbot. What I'm currently working on is to perform a method for a user to make a purchase of an order that is stored in firebase realtime database.
The method is set as the method for an actionMap and the actionMap is linked to an intent for knowing when to call the method and for retrieving the parameters.
My current method uses a simple check for a user's existence and status within the database before identifying the existence of the order they're trying to make a purchase for by its id by going through the user's reference path and doing a .forEach to check every order found and look at its parent folder name to check if it matches the user's order id. My code is as follows:
const MakePurchaseACTION = 'Make Purchase';
function makePurchase(app){
let email = parameter.email;
let orderId = parameter.orderId;
var currDate = currDateGenerator();
var name = email.split(".com");
//Check if User exists first in database
var userRef = database.ref().child('user/' + name);
return userRef.once('value').then(function(snapshot) {
if (snapshot.exists()) {
let statusRetrieved = snapshot.child('Status').val();
//Check if user's status in database is signed in.
if (statusRetrieved == "Signed In") {
var orderRef = database.ref().child('order/' + name);
//Check the order table for the user.
return orderRef.once('value').then(function(orderSnapshot){
let orderVal = orderSnapshot.val();
console.log(orderVal);
//Check through every child for the matching id.
orderSnapshot.forEach(function(childSnapshot) {
let orderIdFound = childSnapshot.key;
//let cost = childSnapshot.child('Cost').val();
console.log(orderIdFound);
if(orderId == orderIdFound) {
let eateryName = childSnapshot.child('Eatery').val();
let eateryLocation = childSnapshot.child('EateryLocation').val();
let deliveryAddress = childSnapshot.child('DeliveryAddress').val();
let orderItem = childSnapshot.child('OrderItem').val();
let quantity = childSnapshot.child('Quantity').val();
let cost = childSnapshot.child('Cost').val();
var purchaseRef = database.ref().child('purchase/' + name + "/" + currDate + "/" + orderId);
purchaseRef.set({
"Eatery" : eateryName,
"EateryLocation" : eateryLocation,
"DeliveryAddress": deliveryAddress,
"OrderItem" : orderItem,
"Quantity": quantity,
"Cost": cost,
"DateCreated": currDate
});
app.add("You have successfully purchased Order " + orderId);
} else {
app.add("There is no order with that id.");
}
});
});
} else {
app.add("You need to be signed in before you can order!");
}
}
else {
app.add("Sorry pal you don't exist in the database.");
}
});
}
actionMap.set(MakePurchaseACTION, makePurchase);
After checking through some firebase logs
Firebase Logs screenshot here
Firebase Realtime Database Order Table Sample
I found that the method actually completes Purchase table sample but my dialogflow returns with the stated error of:
Error: No responses defined for platform: undefined and displays "Not Available" back to the user. My question is how do I go about resolving this error?

Twilio Client CallSid Getting Changed in JavaScript

I've implemented a call center in Salesforce with Twilio client JavaScript SDK. I'm trying to save the call record information in Salesforce and I'm using the connection.parameters.CallSid to identify the correct record when the recording call back fires. However my CallSid in client side is getting changed automatically sometimes to a different format and hence the recording call back function can't find the Salesforce end record to update it with the RecordingUrl. Have anyone experienced this before or appreciate any guidance.
Below is my JavaScript code. To be more specific, in the startCall function console.log print the CallSid correctly but when goes to saveLog function it's having a different value with a different format and hence the saved record having an incorrect value.
<script type="text/javascript">
Twilio.Device.setup("{! token }");
var callerSid; // hold the Twilio generated CallSid unique to this call
var parentId; // hold the parent record being called in order to associate as the parent of task being logged for the call
var newTaskId; // hold the id of newly created task
// function to fire when click 2 dial executes
var startCall = function (payload) {
sforce.opencti.setSoftphonePanelVisibility({visible: true}); //pop up CTI softphone
parentId = payload.recordId; // the record that the phone number being called belongs to
var cleanednumber = cleanFormatting(payload.number);
params = {"PhoneNumber": cleanednumber};
var connection = Twilio.Device.connect(params);
callerSid = connection.parameters; // track the unique Twilio CallSid
console.log('clk2dial : ', callerSid.CallSid); **// here it logs correcly as CAc57d05994cd69498e0353a5f4b07f2dc**
setTimeout(function(){
saveLog(); // save the call information in a Task record
}, 2000
);
};
//OpenCTI!!
sforce.opencti.enableClickToDial();
sforce.opencti.onClickToDial({listener : startCall}); // click 2 dial
function cleanFormatting(number) {
//changes a SFDC formatted US number, which would be 415-555-1212 into a twilio understanble number 4155551212
return number.replace(' ','').replace('-','').replace('(','').replace(')','').replace('+','');
}
// save the call information in a Task record
function saveLog() {
var keyPrefix;
var taskToSave;
console.log('callerSid.CallSid : ', callerSid.CallSid); **// surprisingly here it logs as TJSce253eb4-c2a0-47f3-957f-8178e95162aa**
if(parentId != null) {
keyPrefix = parentId.slice(0,3);
}
if(keyPrefix != null && keyPrefix == '003') {
taskToSave = {WhoId:parentId, Type: "Call", CallObject: callerSid.CallSid, entityApiName: "Task", Subject: "Call log"};
} else {
taskToSave = {WhatId:parentId, Type: "Call", CallObject: callerSid.CallSid, entityApiName: "Task", Subject: "Call log"};
}
sforce.opencti.saveLog({value:taskToSave, callback: saveLogCallBack});
}
// call back function for saving the call information in a Task record
var saveLogCallBack = function(response) {
if(response.success) {
newTaskId = response.returnValue.recordId;
console.log('save success! : ', newTaskId);
} else {
console.error('Error saving : ', response.errors);
}
}
</script>
Answering my own question as I got through this. I registered a function for Twilio.Device.connect and in the call back function retrieved the CallSid. Along with that I've updated my click 2 dial function as well accordigly as below. However I was unable to find this approach in Twilio documentation and any comments are welcome.
// function to fire when click 2 dial executes
var startCall = function (payload) {
sforce.opencti.setSoftphonePanelVisibility({visible: true}); //pop up CTI softphone
parentId = payload.recordId; // the record that the phone number being called belongs to
var cleanednumber = cleanFormatting(payload.number);
params = {"PhoneNumber": cleanednumber};
Twilio.Device.connect(params);
};
//OpenCTI!!
sforce.opencti.enableClickToDial();
sforce.opencti.onClickToDial({listener : startCall}); // click 2 dial
// registered a function for Twilio Device connect
Twilio.Device.connect(function(response) {
callSid = response.parameters; // track the unique Twilio CallSid
// nothing change in save function so not posting again
saveLog(); // save the call information in a Task record
});

MongoDB - Mongoose - TypeError: save is not a function

I am attempting to perform an update to a MongoDB document (using mongoose) by first using .findById to get the document, then updating the fields in that document with new values. I am still a bit new to this so I used a tutorial to figure out how to get it working, then I have been updating my code for my needs. Here is the tutorial: MEAN App Tutorial with Angular 4. The original code had a schema defined, but my requirement is for a generic MongoDB interface that will simply take whatever payload is sent to it and send it along to MongoDB. The original tutorial had something like this:
exports.updateTodo = async function(todo){
var id = todo.id
try{
//Find the old Todo Object by the Id
var oldTodo = await ToDo.findById(id);
}catch(e){
throw Error("Error occured while Finding the Todo")
}
// If no old Todo Object exists return false
if(!oldTodo){
return false;
}
console.log(oldTodo)
//Edit the Todo Object
oldTodo.title = todo.title
oldTodo.description = todo.description
oldTodo.status = todo.status
console.log(oldTodo)
try{
var savedTodo = await oldTodo.save()
return savedTodo;
}catch(e){
throw Error("And Error occured while updating the Todo");
}
}
However, since I don't want a schema and want to allow anything through, I don't want to assign static values to specific field names like, title, description, status, etc. So, I came up with this:
exports.updateData = async function(update){
var id = update.id
// Check the existence of the query parameters, If they don't exist then assign a default value
var dbName = update.dbName ? update.dbName : 'test'
var collection = update.collection ? update.collection : 'testing';
const Test = mongoose.model(dbName, TestSchema, collection);
try{
//Find the existing Test object by the Id
var existingData = await Test.findById(id);
}catch(e){
throw Error("Error occurred while finding the Test document - " + e)
}
// If no existing Test object exists return false
if(!existingData){
return false;
}
console.log("Existing document is " + existingData)
//Edit the Test object
existingData = JSON.parse(JSON.stringify(update))
//This was another way to overwrite existing field values, but
//performs a "shallow copy" so it's not desireable
//existingData = Object.assign({}, existingData, update)
//existingData.title = update.title
//existingData.description = update.description
//existingData.status = update.status
console.log("New data is " + existingData)
try{
var savedOutput = await existingData.save()
return savedOutput;
}catch(e){
throw Error("An error occurred while updating the Test document - " + e);
}
}
My original problem with this was that I had a lot of issues getting the new values to overwrite the old ones. Now that that's been solved, I am getting the error of "TypeError: existingData.save is not a function". I am thinking the data type changed or something, and now it is not being accepted. When I uncomment the static values that were in the old tutorial code, it works. This is further supported by my console logging before and after I join the objects, because the first one prints the actual data and the second one prints [object Object]. However, I can't seem to figure out what it's expecting. Any help would be greatly appreciated.
EDIT: I figured it out. Apparently Mongoose has its own data type of "Model" which gets changed if you do anything crazy to the underlying data by using things like JSON.stringify. I used Object.prototype.constructor to figure out the actual object type like so:
console.log("THIS IS BEFORE: " + existingData.constructor);
existingData = JSON.parse(JSON.stringify(update));
console.log("THIS IS AFTER: " + existingData.constructor);
And I got this:
THIS IS BEFORE: function model(doc, fields, skipId) {
model.hooks.execPreSync('createModel', doc);
if (!(this instanceof model)) {
return new model(doc, fields, skipId);
}
Model.call(this, doc, fields, skipId);
}
THIS IS AFTER: function Object() { [native code] }
Which showed me what was actually going on. I added this to fix it:
existingData = new Test(JSON.parse(JSON.stringify(update)));
On a related note, I should probably just use the native MongoDB driver at this point, but it's working, so I'll just put it on my to do list for now.
You've now found a solution but I would suggest using the MongoDB driver which would make your code look something along the lines of this and would make the origional issue disappear:
// MongoDB Settings
const MongoClient = require(`mongodb`).MongoClient;
const mongodb_uri = `mongodb+srv://${REPLACE_mongodb_username}:${REPLACE_mongodb_password}#url-here.gcp.mongodb.net/test`;
const db_name = `test`;
let db; // allows us to reuse the database connection once it is opened
// Open MongoDB Connection
const open_database_connection = async () => {
try {
client = await MongoClient.connect(mongodb_uri);
} catch (err) { throw new Error(err); }
db = client.db(db_name);
};
exports.updateData = async update => {
// open database connection if it isn't already open
try {
if (!db) await open_database_connection();
} catch (err) { throw new Error(err); }
// update document
let savedOutput;
try {
savedOutput = await db.collection(`testing`).updateOne( // .save() is being depreciated
{ // filter
_id: update.id // the '_id' might need to be 'id' depending on how you have set your collection up, usually it is '_id'
},
$set: { // I've assumed that you are overwriting the fields you are updating hence the '$set' operator
update // update here - this is assuming that the update object only contains fields that should be updated
}
// If you want to add a new document if the id isn't found add the below line
// ,{ upsert: true }
);
} catch (err) { throw new Error(`An error occurred while updating the Test document - ${err}`); }
if (savedOutput.matchedCount !== 1) return false; // if you add in '{ upsert: true }' above, then remove this line as it will create a new document
return savedOutput;
}
The collection testing would need to be created before this code but this is only a one-time thing and is very easy - if you are using MongoDB Atlas then you can use MongoDB Compass / go in your online admin to create the collection without a single line of code...
As far as I can see you should need to duplicate the update object. The above reduces the database calls from 2 to one and allows you to reuse the database connection, potentially anywhere else in the application which would help to speed things up. Also don't store your MongoDB credentials directly in the code.

Asynchronous variables in for loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I'm working on adding notifications to my chrome extension that lets users chat with one another. Each user has a chats section that lists all the chatrooms they're in, along with the last message they saw. To check if a message was sent while they were away, I'm trying to loop through the chatrooms they're in and seeing if the last message sent was added to the database after the last message they saw was added.
Here's my code, I'm using a noSQL database called firebase:
var checkNotifications = function(user){
var notification = false;
firebase.database().ref('users/'+user+'/chats').once('value', function(snapshot){
for (var chat in snapshot.val()){
var lastMessage = snapshot.val()[chat];
firebase.database().ref('chats/'+chat+'/msgs').once('value', function(snap){
if (Object.keys(snap.val())[0] > lastMessage){
notification = true; // Message is newer than their last seen message
}
});
}
});
}
I'm running into the issue where before the second database call to return the messages from the chatroom currently being looked at in the for loop the for loop already moves on and updates the variable lastMessage, so that variable ends up holding the last message from a chatroom further down the chain.
Is there a way to make this less asynchronous so that the variable lastMessage has the same value for each step in the for loop?
To check if a message was sent while they were away, I'm trying to
loop through the chatrooms they're in and seeing if the last message
sent was added to the database after the last message they saw was
added.
transactions take a function and are the proper tool for this.
When working with data that could be corrupted by concurrent
modifications, such as incremental counters, you can use a transaction
operation. You can give this operation an update function and an
optional completion callback. The update function takes the current
state of the data as an argument and returns the new desired state you
would like to write. If another client writes to the location before
your new value is successfully written, your update function is called
again with the new current value, and the write is retried.
For instance, in the example social blogging app, you could allow users to star and unstar posts and keep track of how many stars a post has received as follows:
function toggleStar(postRef, uid) {
postRef.transaction(function(post) {
if (post) {
if (post.stars && post.stars[uid]) {
post.starCount--;
post.stars[uid] = null;
} else {
post.starCount++;
if (!post.stars) {
post.stars = {};
}
post.stars[uid] = true;
}
}
return post;
});
}
This should work. It captures the variable in a closure: (function(){ ... })();
var checkNotifications = function(user){
var notification = false;
firebase.database().ref('users/'+user+'/chats').once('value', function(snapshot){
for (var chat in snapshot.val()){
(function(){
var lastMessage = snapshot.val()[chat];
firebase.database().ref('chats/'+chat+'/msgs').once('value', function(snap){
if (Object.keys(snap.val())[0] > lastMessage){
notification = true; // Message is newer than their last seen message
}
});
})();
}
});
}
Or this:
var checkNotifications = function(user){
var notification = false;
firebase.database().ref('users/'+user+'/chats').once('value', function(snapshot){
var func = function(lastMessage) {
firebase.database().ref('chats/'+chat+'/msgs').once('value', function(snap){
if (Object.keys(snap.val())[0] > lastMessage){
notification = true; // Message is newer than their last seen message
}
});
};
for (var chat in snapshot.val()){
func(snapshot.val()[chat]);
}
});
}

Firebase Update just a Parent Node

This is a small question and if need be I'll just rewrite everything, but I want to save myself the work.
I have a structure that looks like users/usernames/<someUN>/. I checked out the Firebase documentation but I couldn't find examples of how to update in a 'tight' tree.
Now if I want to change <someUN>, you can see the problem
this.database.ref('users/usernames/' + this.UN).update({
username: newUsernameVariable
})
I would have to restructure an unchangable value and do something like users/usernames/<userID>/username/<username> but
it goes against denormalizing the database and
I already have a tree holding uids/<uid>/usernames/<UN>, so that would be extra redundant
Now if you tried to move the ref up a notch:
this.database.ref('users/usernames').update({
this.UN: newUsernameVariable
})
This is very close to what I want but unfortunately is not valid JSON. The left hand side is not converted to string. I've tried doing this
var UNJSON = JSON.stringify(this.UN);
this.database.ref('users/usernames/').update({
UNJSON: newUsername
});
But it won't work, just treats UNJSON as a word
EDIT:
I've changed it to
var updates = {};
updates[this.UN] = newUsername;
this.database.ref('users/usernames').update(updates);
Which almost works, but now the children node are replaced!
I've changed the question of this title because essentially I've gotten to the point where I have something like users/usernames/myawesomeusername/{manychildren} and I want to keep the children while editing myawesomeusername.
EDIT 2: this.UN is populated in onAuthStateChanged by the time it hits the update code. Here is the setting of this.UN
// UN is a global read/write username string that persists throughout the session.
// SETTING THE VALUE OF this.UN WITH UID
if(this.UN == undefined) {
console.log('this.UN was null. Fetch the real one with UID from the database');
this.database.ref('uids/' + user.uid).once('value', function(snapshot){
this.UN = snapshot.val().username;
console.log('Grabbed from snapshot.username');
if(this.UN == undefined) {
console.log('Impossible error');
}
}.bind(this)).catch(function(err){
console.log('Error obtaining userID from database', err);
this.UN = user.displayName || "User" + user.uid;
}.bind(this));
} else {
console.log(this.UN);
}
I use this.UN to handle any time I need the username for the rest of the app.

Categories

Resources