Database Reference
In-Depth Information
The state for the counter object is, for the moment, stored in the object
itself. A more complicated dashboard would persist this data somewhere to
survive restarts. This issue is tackled later in this section.
Updating counter state is handled through methods on the counter object.
The basic operations to support are the get , set , and increment
methods:
Counter.prototype.state = function(cb) {
return cb(null,this._state);
};
Counter.prototype.get = function(counter,cb) {
return cb(null,this._state[counter] || 0);
};
Counter.prototype.set = function(counter,value,cb) {
this._state[counter] = (value || 0);
this.emit("updated",counter,this._state[counter]);
return cb(null,this._state[counter]);
};
Counter.prototype.increment =
function(counter,amount,cb) {
var self = this;
this.get(counter,function(err,count) {
self.set(counter,count + 1*(amount||1),cb);
})
};
Note that the set method in the preceding code emits an updated event
whenever a counter is changed. This is the primary interaction any
streaming connection has with the counters. It simply listens to this event
when the connection is opened and removes itself from the set of listeners
when the connection closes.
Now that the counter state can be maintained on the server side, a simple
API is needed to allow updates to the state. This will then be attached to the
client-side interface via both SSEs and WebSockets in the next two sections.
Express makes it easy to implement simple REST-style APIs to the counter
singleton, as seen in this code found in dashboard/index.js :
Search WWH ::




Custom Search