Get Time in firebase database using angularfire2 - firebase

I am using Angularfire2 and I'm tesing to build a chat app that pushes messages in the database. I want to get the time when the data is pushed. Your help is really appreciated. Thanks a lot!

Firebase uses a constant value which is replaced with a numeric timestamp when it is written to the database. This removes the need to track and synchronize the time across clients.
firebase.database.ServerValue.TIMESTAMP
You can then read the value of the reference that was just written to see the exact time.
var sessionsRef = firebase.database().ref('sessions');
var mySessionRef = sessionsRef.push();
mySessionRef.update({ startedAt: firebase.database.ServerValue.TIMESTAMP });
mySessionRef.once('value').then(function(dataSnapshot) {
var time = dataSnapshot.child('startedAt'); // the time when the data was written
});

firebase.database['ServerValue']['TIMESTAMP']

Related

equalTo() is failing to return expected response

Needed Details
I am using Dialogflow fulfillment for my project along with Firebase realtime database. My database has a structure:
Let me first tell you about the structure of the database. It has got a list of ATMs(automated teller machine) with its full address and other needful information. I need to fetch all the ATMs with a given value of Pin number, and the given value of Pin number will come from an API response. This Pin number is nothing but the Zip Code for that ATM. So obviously, with a Pin number, there can be many ATMs.
My problem
Below is the code I am using to make an API call and Firebase database querying with received Pin value as the response from API.
var ref = db.ref("atms/");
var response = await axios.get('some URL'); //API call
var zipcodes = response.data.search_results; // Array of Pin values
console.log(zipcodes[2].postal_code); //This prints a Pin value 721304, which confirms successful response from API
ref.orderByChild("Pin").equalTo(zipcodes[2].postal_code).on("child_added", function(snapshot) { //this line is the problem
console.log(snapshot.val());
});
But the above code with equalTo(zipcodes[2].postal_code) does not give any response. But when I replace it with equalTo(721304), it does give an expected response. To emphasize, both equalTo(zipcodes[2].postal_code) and equalTo(721304) are necessarily same.
I need to use this equalTo(zipcodes[2].postal_code) only because I will be running a loop over this query, which is because of the need to query many, many Pin at once.
Could you please help me understand what is wrong here and how do I implement what I am trying to do here? Please let me know in case of any follow-up questions.
As shown by console.log(typeof zipcodes[2].postal_code); (see comments above), the value of zipcodes[2].postal_code is not of type number but of type string. You need to convert it to number, as follows:
ref.orderByChild("Pin").equalTo(Number(zipcodes[2].postal_code)).on("child_added", function(snapshot) { //this line is the problem
console.log(snapshot.val());
});

I am having a problem with Firebase Auth-UI user metadata

I am using Firebase Auth UI to register and store users in my app.
When the user is new in the app, I need to register some things, so I need to know when a user is new or not.
According to the documentation I am using the right way to check new users:
Auth-UI Metadata
The way I check to know wheter a user is new or not is comparing the metadata, user creation timestamp and Last Signed Timestamp and it worked perfect.
if (metadata.getCreationTimestamp() == metadata.getLastSignInTimestamp()){
//do some new user stuff
}else{
//log in old user
}
This code is not working right now, because they might have changed something.
The last time I am sure this code worked is the 30th of January.
There is a little difference in miliseconds between the creation timestamp and the sign in timestamp when the user is new:
Creation timestamp: 1549462011000 Last Sign in Timestamp: 1549462011028
I've tried in two different Firebase projects and the problem is the same.
Can anyone help?
I experienced the same problem with my app.
The two timestamps have now few milliseconds difference.
A way to fix it is to check the two timestamps are close enough ( 3 seconds in the code below)
val signUpInterval = 3000L
val isNewUser = Math.abs(metadata.creationTimestamp - metadata.lastSignInTimestamp) < signUpInterval

How to update a document value with firebase cloud function

How can i update the value of a document on changing the value of another document.
I have raw-material document and finished-product document.
What i want to do is on changing the price of raw-material i want to update the price of finished-material
How can i do so ???
My code is like this so far
export const rawMaterialPriceChange = functions.database.ref('/raw-materials/{key}').onUpdate((snapshot)=>{
console.log('My key',snapshot.after.key);
var priceDiff = parseFloat(snapshot.after.val().price)-parseFloat(snapshot.before.val().price);
<HERE I WANT TO REFER ANOTHER DOCUMENT WITH SAME KEY AND UPDATE ITS VALUE
return true;
});
My firebase structure is like this:
Can anyone please help me ? Thank you
Found the solution from the following threads
Firebase HTTP Cloud Functions - Read database once
How to run query from inside of Cloud function?

Firebase and Angularfire nightmare migration for Update

I am new to firebase and I am having a bit of a nightmare trying to adapt old code to what is now deprecated and what is not. I am trying to write a function which updates one "single" record in my datasource using the now approved $save()promise but it is doing some really strange stuff to my data source.
My function (should) enables you to modify a single record then update the posts json array. However, instead of doing this, it deletes the whole datasource on the firebase server and it is lucky that I am only working with testdata at this point because everything would be gone.
$scope.update = function() {
var fb = new Firebase("https://mysource.firebaseio.com/Articles/" + $scope.postToUpdate.$id);
var article = $firebaseObject(ref);
article.$save({
Title: $scope.postToUpdate.Title,
Body: $scope.postToUpdate.Body
}).then(function(ref) {
$('#editModal').modal('hide');
console.log($scope.postToUpdate);
}, function(error) {
console.log("Error:", error);
});
}
Funnily enough I then get a warning in the console "after" I click the button:
Storing data using array indices in Firebase can result in unexpected behavior. See https://www.firebase.com/docs/web/guide/understanding-data.html#section-arrays-in-firebase for more information. Also note that you probably wanted $firebaseArray and not $firebaseObject.
(No shit?) I am assuming here that $save() is not the right call, so what is the equivalent of $routeParams/$firebase $update()to do a simple binding of the modified data and my source? I have been spending hours on this and really don't know what is the right solution.
Unless there's additional code that you've left out, your article $firebaseObject should most likely use the fb variable you created just before it.
var article = $firebaseObject(fb);
Additionally, the way in which you're using $save() is incorrect. You need to modify the properties on the $firebaseObject directly and then call $save() with no arguments. See the docs for more.
article.Title = $scope.postToUpdate.Title;
article.Body = $scope.postToUpdate.Body;
article.$save().then(...

When I connect to firebase, I only see the structures and no devices (Nest API)

I am trying to read basic information about thermostats using the methods in the thermostat control example (https://developer.nest.com/documentation/control), but when I connect to firebase I only see the structure object (which only contains name, away, smoke_co_alarms, structure_id and thermostats) in the snapshot– There is no devices object. I am connecting to firebase using
var nestToken = $.cookie('nest_token');
var dataRef = new Firebase('wss://developer-api.nest.com/');
dataRef.auth(nestToken);
I tried to connect directly to devices using wss://developer-api.nest.com/devices, but that only returns an undefined data-structure.
I've also tried connecting to firebase using https://developer-api.nest.com/ and https://developer-api.nest.com/, but they raised an authorization error and caused my javascript to go into an infinite loop sending requests.
I'm reading data using:
dataRef.on('value', function (snapshot) {
var data = snapshot.val();
structure = firstChild(data.structures);
console.log(data);
console.log(data.structures);
console.log(data.devices);
console.log(data.devices.thermostats);
console.log(structure.thermostats);
};
Lastly, I tried it on an account with real devices and one with virtual devices, so I know that couldn't be causing it (even though I didn't expect it to).
Any ideas what I am doing wrong? The issue couldn't be in my App.js file, could it? Is there some configuration I need to do on the user's end in addition to the authentication? I get the feeling it's probably something really simple that's staring me in the face.
So I figured it out: It's a permissions issue. When my client-profile was setup, it only requested permission to read the away/home status. So when I query Firebase it only returns the a snapshot with structure because that is where the away/home status can be read. So, in summary, if you're not seeing the devices structure, even though devices are associated with the user, check your client permissions.
Using (some of) your code, I have no trouble seeing the devices object:
var dataRef = new Firebase('wss://developer-api.nest.com');
dataRef.auth(nestTokenLive);
dataRef.on('value', function (snapshot) {
var data = snapshot.val();
console.log(data);
console.log(data.devices);
});
Results in:
> Object {devices: Object, structures: Object}
> Object {thermostats: Object}

Resources