Only execute if Firebase data changed using nodejs - javascript

I'm writing a script in node.js to keep track of firebase data. I want a line to execute but ONLY when there's a change in the database. Meaning that the first time I execute the code, I don't want It to execute because it successfully read from the database. It should only execute If there's change later on.
Here's my code:
var forumRef = firebase.database().ref("Forum/ForumIds");
forumRef.on('value', function(snapshot) {
console.log("new post");
});
Any help would be great. Thanks!

So with firebase you're always going to get the value of whatever node you are reading when you attach a listener. AFAIK there isn't a way to only receive events when your node changes and not upon initial listener attachment. You're best best is probably to just throw away the first invocation of your callback. There isn't even a way to get the previous value from within your callback to see if it's an actual change event or just a result of attaching the listener. Kinda sucks but ¯_(ツ)_/¯

Related

How can I update DOM while a method is running?

I'm writing a simple tool that works on the client side. Basically, the user brings in a file, presses a button to start it, it does stuff with it (takes about 10-15 seconds), and then it gives the modified file back.
Unfortunately, as soon as they press the button to start the method, the DOM doesn't update until the method is finished, so there's no feedback until it's all finished, which is quite frustrating.
In the template section, I have:
<p v-if="processingStatus==1">Processing data...</p>
The "processingStatus" variable is set to 0 by default.
In the method, which is "processData" and is called when the button is pressed, it starts with
this.processingStatus = 1
And then proceeds to process the data.
Unfortunately, the "Processing data..." tag doesn't show up until the method is finished. How can I force VueJS to render the DOM while the method is running?
Based on what you are saying that processData is doing (going through a bunch of data in arrays), my guess is that it is not running async and is locking the javascript thread until it is done.
What you need to do is inside processData is set the is processing variable like you are, but then do all the actual work inside a promise or some other mechanism to release control and update the UI.
Potentially you could also call
vm.$forceUpdate();
before starting all your array work.

How to constantly get Information from the Backend into the dom in node?

I got a question concerning the relationship of the DOM and my Backend. I have a website running with node.js and express and now I want to implement a "live counter" feature.
The counter should actualize every 10 seconds or so and show the user the current "score". The problem is that this score is saved in my Mongo-Database and but I want to show the new information to the user (without loading a completely new page, this would be annoying).
It is no problem for me to run a script that actulizes every seconds or so, but I either had to:
1) Let a script run on the client side and retrieve information from my DB like this:
setInterval(function(){
//get Information from Server (X)
//manipulate div in the DOM
}, 1000
);
Or 2) Let a script run on the server side and somehow manipulate the DOM from there
setInterval(function(){
//get value from DB
//somehow access DOM and change the value there (X)
}, 1000
);
(The "(X)" marks the tricky part for me)
I also know that it is not really possible to manipulate the DOM from node and not a good idea to access my DB from the clientside. But I am out of ideas here. Can some of you explain to me how this problem could be solved?
Thanks a lot,
Paul
You can use socket.io for this type of problem where you can emit the data from your server on specific time interval or on any specific event. And then subscribe that event to get that data in realtime.

How to abort creation into firebase realtime database from a cloud function?

I'm creating an application that uses two step object creation into firebase realtime database.
What I want is that on a cloud function that catches onCreate event, if some rules are not complete, then the create action be stopped.
Is there a way to do that? Or I need to remove the node instead of reject the creation?
Thank you!
You might want to consider a command-response model for database writes. Instead of writing directly into the database and expecting that a function cancel the write, push a "command" object into the database that describes what you want to do, at a different location, and have a function respond to that command to determine what should actually be done. Your function can then determine whether or not to commit a final write if the conditions are OK.
I gave a talk at Google I/O 2017 that outlines this strategy with respect to a multi-player turn based game that intercepts all move requests to determine if they're valid before committing them to the game. The part about command-response starts here.
There currently is no way to reschedule a trigger. So indeed, you'll either have to create a new node or trigger a re-check in some other way, e.g. a regular cron trigger to clean up the previously unhandled nodes (blog, video).

JavaScript callbacks and control flow

When are callbacks executed, for example the callback of a setTimeout() or a click event?
Do they pause code, that is already running, or do they wait until it has finished?
Example
I have a data structure (incrementalChanges) that records state changes caused by user interactions, for example mouse clicks. If I want to send all changes to another peer, I send him this data structure.
Another possibility is a full synchronisation (makeFullSync()), that means I send him my complete current state, so that I must empty the incremental changes (deleteIncrementalChanges()). That is, what you can see in the code. However I am not sure, what happens, if a user clicks something exactly between these two function calls. If this event fires immediately, then an item to the incrementalChanges structure would be added, but then in the second call directly deleted, so that it will never be sent and the other peer's state would became invalid.
makeFullSync();
/* what if between these 2 calls a new change is made, that is saved in the
changes data structure, that will be deleted by deleteIncrementalChanges()?
Then this change would be lost? If I change the order it is not better ...
*/
deleteIncrementalChanges();
Some good links and, in the case the first scenario (it pauses running code) is true, solutions are welcomed.
Javascript is single threaded, and keeps an event stack of stuff it needs to get to once it's done running the current code it's working on. It will not start the next event in the stack until the current one is finished.
If you make multiple asynchronous calls, such as calls for a server to update data on another client, you need to structure your code to handle the case where they don't necessarily reach the second client in the same order.
If you're sending changes one at a time to another user, you can time stamp the changes to track what order they were made on the first client.
Do they pause code, that is already running, or do they wait until it has finished?
They wait until it has finished. JavaScript is single threaded, more than one piece of code can not run at once. JS uses an event loop to handle asynchronous stuff. If an event such as a click handler or timer firing happens while another piece of code is running, that event is queued up and runs after the currently running code finishes executing.
Assuming makeFullSync(); and deleteIncrementalChanges(); are called in the same chunk of code they will be executed one after another without any click events being processed until after they have both run.
One almost exception to the nothing runs in parallel rule in JS is WebWorkers. You can send data off to a worker for processing which will happen in another thread. Even though they run in parallel their results are inserted back into the event loop like any other event.

Node.js: Connecting to a Server Using Sockets

I'm just starting to play with Node.js today, and thought I'd start with what I thought would be a simple script: Connecting to a server via sockets, and sending a bit of data, and receiving it back. I'm creating a command line utility. Nothing in the browser.
An example of a server would be memcached, beanstalkd, etc. It seems the net module is the right tool for the job, but I'm still a bit fuzzy on the Node.js way of doing things. Some help would be appreciated.
Update #1
Let me see if I can break this down in into a couple smaller questions. I hate even asking questions like this, but the Node.js documentation is very sparse, and most documentation written 6 months ago is already out dated.
1) So I can use net.stream.write() to send data to the remote server, but I don't know how to get a response back. I'm not even sure how to test when write() is finished, because it doesn't take a callback.
2) A few clues on how the whole event.emit thing works would be great. I think that's really the key stone I'm missing in those whole thing.
Update #2
Here's where I'm still confused on implementing a client program. Let me diagram a typical send request => get response system:
1) I bind callbacks to the net module to get responses and other events, including the necessary bindings to get a response from the server.
2) I use stream.write() to send a request to the server.
3) I then do nothing, because my bound "data" event will get the response from the server.
Here's where things get tricky. Suppose I call stream.write() twice before my bound "data" event is called. Now I have a problem. When the "data" event does happen, how do I know which of the 2 requests it's a response for? Am I guaranteed that responses will take place in the same order as requests? What if responses come back in a different order?
First of all, let's make clear what a EventEmitter is. JavaScript and therefore Node.js are asynchronous. That means, instead of having to wait for incoming connections on a server object, you add a listener to the object and pass it a callback function, which then, "as soon" as the event happens, gets executed.
There's still waiting here and there going on in the background but that has been abstracted away from you.
Let's take a look at this simple example:
// #1) create a new server object, and pass it a function as the callback
var server = net.createServer(function (stream) {
// #2) register a callback for the 'connect' event
stream.on('connect', function () {
stream.write('hello\r\n'); // as
});
// #3) register a callback for the 'data' event
stream.on('data', function (data) {
stream.write(data);
});
// #4) register a callback for the 'end' event
stream.on('end', function () {
stream.write('goodbye\r\n');
stream.end();
});
});
// #5) make the server listen on localhost:8124
server.listen(8124, 'localhost');
So we create the server and pass it the callback function, this function is not yet executed. Passing the function here is basically a shortcut for adding a listener for the connection event of the server object. After that we start the server at #5.
Now what happens in the case of an incoming connection?
Since the function we passed to createServer was bound to the connection event, it now gets executed.
It adds the connect, data and end event listeners to the stream object (which represents the individual connection) by hooking up callbacks for the events.
After that, the stream fires the connect event, therefore the function passed at #2 gets executed and writes hello\r\n to the stream. How does the function know which stream it should write to? Closures are the answer, the function inherits the scope it was created in, therefore inside the function stream is still referencing to the individual connection that triggered this very callback we're in right now.
Now the client sends some data over the connection, which makes the stream object call its data event, since we bound a function to this event at #3 we now echo the incoming data back to the client.
In case the client closes the connection, the function we've bound at #4 gets called, which writes goodbye\r\n and after that closes the connection from our side.
Does this make things a little bit more clear? Well it definitely makes the whole thing a lot easier. Node is, just as well as JavaScript is inside Browsers, single threaded. There's only one thing happening at a given point time.
To describe it simple, all these callbacks end up in a global queue and are then called one after another, so this queue may(abstracted) look like this:
| connection event for a new stream
| data event for stream #12
| callback set via setTimeout
v close event of yet another stream
These are now get executed top to bottom, nothing will ever happen in between those. There's no chance, that while you're doing something in the callback bound to the data event, something will other will happen and magically change the state of the system. Even if there is a new incoming connection on the server, its event will get queued up and it will have to wait until everything before it, including the data event you're currently in, finishes.

Categories

Resources