Is it possible to implement observer pattern using REST API - node.js

I am a newbie to patterns and was wondering whether it is possible to implement observer pattern using REST api. My current view is that it is not possible since REST is more of a pull architecture while observer is more of a push architecture.
Your thoughts are welcome.

An object maintains a list of dependents/observers and notifies them automatically on state changes. To implement the observer pattern, EventEmitter comes to the rescue
// MyFancyObservable.js
var util = require('util');
var EventEmitter = require('events').EventEmitter;
function MyFancyObservable() {
EventEmitter.call(this);
}
util.inherits(MyFancyObservable, EventEmitter);
This is it; we just made an observable object! To make it useful, let's add some functionality to it.
MyFancyObservable.prototype.hello = function (name) {
this.emit('hello', name);
};
Great, now our observable can emit event - let's try it out!
var MyFancyObservable = require('MyFancyObservable');
var observable = new MyFancyObservable();
observable.on('hello', function (name) {
console.log(name);
});
observable.hello('john');
for more details follow the link
Fundamental Node.js Design Patterns
Immediate State Updates for REST/HTTP APIs using Observer Pattern

Related

access data from this nodeJS function

I want to use "data" outside of this function. Please can some one show me how?
resemble('/Users/User/Documents/dev/engineerappcopy/VGimages/'+deviceName+'.png')
.compareTo('/Users/User/Documents/dev/engineerappcopy/VGimages/'+"nexUpdate"+'.png')
.ignoreColors().onComplete(function(data) {
browser.sleep(5000)
console.log(data);
data.getDiffImage().pack().
pipe(fs.createWriteStream('/Users/User/Documents/dev/engineerappcopy/VGimages/'+deviceName+'VG.png'));
});
I am aware that this is asynchronous, however I am struggling with this.
I would suggest you to use EventEmitters. You can use this if at all you want to indicate if any action is finished and optionally you can pass the data as well.
Create a new javscript file 'my-emitter.js'
my-emitter.js (ES6 version)
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
module.exports = myEmitter;
OR
my-emitter.js (Javascript version)
var EventEmitter = require('events').EventEmitter;
var util = require('util');
function MyEmitter(){
EventEmitter.call(this);
}
util.inherits(MyEmitter,EventEmitter);
myEmitter = new MyEmitter();
module.exports = myEmitter;
Your code snippet:
(Check the comments in the code). Emit an event saying that data is available after the async operation is complete
myEmitter.emit('img-op-complete',data);
var myEmitter = require('./my-emitter.js'); //Get your emitter from the module
resemble('/Users/User/Documents/dev/engineerappcopy/VGimages/'+deviceName+'.png')
.compareTo('/Users/User/Documents/dev/engineerappcopy/VGimages/'+"nexUpdate"+'.png')
.ignoreColors().onComplete(function(data) {
browser.sleep(5000)
//Emit the event that data is available and pass the data
myEmitter.emit('img-op-complete',data);
console.log(data);
data.getDiffImage().pack().
pipe(fs.createWriteStream('/Users/User/Documents/dev/engineerappcopy/VGimages/'+deviceName+'VG.png'));
});
othermodule.js
Where ever you want the data (if in other module), use the below piece of code
var myEmitter = require('./my-emitter.js'); //Get your emitter from the module
myEmitter.on('img-op-complete', function(data){
console.log(data); //You'll get your data here after op is done
})
Fore more info on events, https://nodejs.org/dist/latest-v6.x/docs/api/events.html
NOTE:
Promises is also nice solution, but if you use promises good design if data is needed within the same module. But events present a good design pattern in node.js
I would suggest go with promises, you would be able to use this promise across module also if you export it.
There are some really nice articles about how to use promises like Promise.
Coming to how to approach the above issue via promises,
function foo(){
return new Promise(function(resolve,reject){
resemble(<yourPath>)
.compareTo(<yourPath>)
.ignoreColors().onComplete(function(data) {
//for best practice do handle errors
if(err<anyError>){
reject(err);
} else{
resolve(data);
}
});
})
}
Now You can use the above promise where you want to use the data variable :
foo().then(function(<data>){
//do whatever you wish to do with the data
}).catch(function(<err>){
//handle the error
});

Adding or removing EventEmitter.call(this) in my Node example doesn't make any difference, why?

I am new to Node.js and started learning it.
I came across "EventEmitter" in "events" module in node.
After following the example in EventEmitter documentation I wrote the bolow code,
var EventEmitter = require("events");
var util = require("util");
var Ticker = function(){
var self = this;
EventEmitter.call(self);
self.start = function(){
setInterval(function(){
self.emit("tick");
},1000);
}
self.on("tick",function(){
console.log("Keep Ticking");
});
}
util.inherits(Ticker,EventEmitter);
var ticker = new Ticker();
ticker.start();
When I run the code
node example03.js
the output is
rahul#ubuntu:~/rahul/NodePractise/EventEmitter$ node example03.js
Keep Ticking
Keep Ticking
Keep Ticking
Keep Ticking
^C
rahul#ubuntu:~/rahul/NodePractise/EventEmitter$
Now even if I comment the line
//EventEmitter.call(self);
The code works fine.
So whats the purpose of the above line and how is its presence important.
So whats the purpose of the above line and how is its presence
important.
The line of code:
EventEmitter.call(self);
is so the base class (what you inherited from) can properly initialize it's own instance each time you create a new instance of your derived class. This is a very important step that should not be left out.
To explain exactly what it is doing, EventEmitter is the constructor function of the object you derived from. .call(self) is telling Javascript to call that constructor function and to set the this value to the object that was just created (which is pointed to by self in your code). That will end up calling the EventEmitter constructor in the same way as new EventEmitter() would call it which is what you want. The only difference here from new EventEmitter() is that you're pointing this at an instance of your derived object, not at just an EventEmitter object.
In all cases of inheritance, you should call the base class constructor so it can properly initialize itself. But, there may be some types of objects that don't really do much in the constructor so things may happen to work if you leave it out. Or they may just seem to work, but there will be problems down the road.
Adding or removing EventEmitter.call(this) in my Node example doesn't
make any difference, why?
If you look at the EventEmitter code on Github, you can see that the EventEmitter constructor does this:
function EventEmitter() {
EventEmitter.init.call(this);
}
And, the .init() method does this:
EventEmitter.init = function() {
this.domain = null;
if (EventEmitter.usingDomains) {
// if there is an active domain, then attach to it.
domain = domain || require('domain');
if (domain.active && !(this instanceof domain.Domain)) {
this.domain = domain.active;
}
}
if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
this._events = {};
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
So, if you fail to call the parent constructor, there will be several instance variables in the EventEmitter object that are not properly initialized. What this does to the code is anyone's guess (it would take further code study and testing to know for sure), but it is not a good thing. Some features might work without this initialization, but it is very likely that other things will not work properly.

Asynchronous function with multiple emit events (futures in meteor)

My use case is to read RSS feed items asynchronously and load them into a meteor collection.
I have the feedparser npm module that does the parsing. It emits three events .on('error'), .on('meta') and .on('readable) with three different outputs.
When I run it in fixtures.js, with just console.log statements to run the output, its working fine.
When I use the same code to insert into a collection, I get errors related to asynchronocity of the function (assuming something to do with fibers)
So, I want to make it into a meteor method using futures as below -
http://www.discovermeteor.com/patterns/5828399
I tried but could not wrap my head around handling multiple events in Futures.
If you just want to push something to db at one point, it's enough to synchronize this call. Other than that, you can do whatever you want asynchronously. For example:
var Fiber = Npm.require('fibers');
var item = {};
var onInit = function() {
// do whatever with item
};
var onData = function() {
// do whatever with item
};
var onFinish = function() {
new Fiber(function(){
Documents.insert(item);
}).run();
};
Although Meteor is a great tool, I think node and its async insight is brilliant, and the best tool for what you are doing. Keep as a plan b having this part of your project be a straight node app.
Otherwise,
async from meteor
and

Inheriting Node.js' eventemitter fails

I'm trying to add the event listener to my class, but it fails, telling me the object has no 'on' method.
Here's the class in its own file:
var events = require('events');
var util = require('util');
var Motion = function Motion (app) {
events.EventEmitter.call(this);
// Load models
app.loadModel('motion', 'motion');
this.on('testevent', function () {
console.log('an event has happened');
});
this.emit('testevent');
}
util.inherits(Motion, events.EventEmitter);
module.exports = Motion;
And here's how I instantiate it:
var Motion = require('./plugins/motion.js');
var motion = new Motion(app);
It looks like you may be asking for the constructor function itself to be an event emitter. Your code makes the objects produced by new with the constructor. i.e., the object motion produced at the end of your snippet should have an on method (as Vadim Baryshev notes, your code should work as you have it if this is the intent, and if that is the case you can ignore the rest of this answer).
If you really want the constructor to emit events, then take a look at this question and the answer I provided to it. However, it's not a great solution, and there appears to be no way of doing it without using the non-standard __proto__.
A better solution is to make a separate event emitter object for the constructor function to use for emissions. As much as I like the constructor-module pattern, it has to be discarded. Many node modules make the module itself the emitter, and have a function exposed by the module as a constructor. For example:
var events = require('events');
var util = require('util');
exports = module.exports = new events.EventEmitter();
exports.Motion = function (app) {
// Load models
app.loadModel('motion', 'motion');
// Emit event
exports.emit('testevent');
};
and to instantiate:
var motion = require('./plugins/motion');
motion.on('testevent', function () {
console.log('an object was constructed');
});
var motionObj = new motion.Motion(app);

Node.js - inheriting from EventEmitter

I see this pattern in quite a few Node.js libraries:
Master.prototype.__proto__ = EventEmitter.prototype;
(source here)
Can someone please explain to me with an example, why this is such a common pattern and when it's handy?
As the comment above that code says, it will make Master inherit from EventEmitter.prototype, so you can use instances of that 'class' to emit and listen to events.
For example you could now do:
masterInstance = new Master();
masterInstance.on('an_event', function () {
console.log('an event has happened');
});
// trigger the event
masterInstance.emit('an_event');
Update: as many users pointed out, the 'standard' way of doing that in Node would be to use 'util.inherits':
var EventEmitter = require('events').EventEmitter;
util.inherits(Master, EventEmitter);
2nd Update: with ES6 classes upon us, it is recommended to extend the EventEmitter class now:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
See https://nodejs.org/api/events.html#events_events
ES6 Style Class Inheritance
The Node docs now recommend using class inheritence to make your own event emitter:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {
// Add any custom methods here
}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
Note: If you define a constructor() function in MyEmitter, you should call super() from it to ensure the parent class's constructor is called too, unless you have a good reason not to.
To inherit from another Javascript object, Node.js's EventEmitter in particular but really any object in general, you need to do two things:
provide a constructor for your object, which completely initializes the object; in the case that you're inheriting from some other object, you probably want to delegate some of this initialization work to the super constructor.
provide a prototype object that will be used as the [[proto]] for objects created from your constructor; in the case that you're inheriting from some other object, you probably want to use an instance of the other object as your prototype.
This is more complicated in Javascript than it might seem in other languages because
Javascript separates object behavior into "constructor" and "prototype". These concepts are meant to be used together, but can be used separately.
Javascript is a very malleable language and people use it differently and there is no single true definition of what "inheritance" means.
In many cases, you can get away with doing a subset of what's correct, and you'll find tons of examples to follow (including some other answers to this SO question) that seem to work fine for your case.
For the specific case of Node.js's EventEmitter, here's what works:
var EventEmitter = require('events').EventEmitter;
var util = require('util');
// Define the constructor for your derived "class"
function Master(arg1, arg2) {
// call the super constructor to initialize `this`
EventEmitter.call(this);
// your own initialization of `this` follows here
};
// Declare that your class should use EventEmitter as its prototype.
// This is roughly equivalent to: Master.prototype = Object.create(EventEmitter.prototype)
util.inherits(Master, EventEmitter);
Possible foibles:
If you use set the prototype for your subclass (Master.prototype), with or without using util.inherits, but don't call the super constructor (EventEmitter) for instances of your class, they won't be properly initialized.
If you call the super constructor but don't set the prototype, EventEmitter methods won't work on your object
You might try to use an initialized instance of the superclass (new EventEmitter) as Master.prototype instead of having the subclass constructor Master call the super constructor EventEmitter; depending on the behavior of the superclass constructor that might seem like it's working fine for a while, but is not the same thing (and won't work for EventEmitter).
You might try to use the super prototype directly (Master.prototype = EventEmitter.prototype) instead of adding an additional layer of object via Object.create; this might seem like it's working fine until someone monkeypatches your object Master and has inadvertently also monkeypatched EventEmitter and all its other descendants. Each "class" should have its own prototype.
Again: to inherit from EventEmitter (or really any existing object "class"), you want to define a constructor that chains to the super constructor and provides a prototype that is derived from the super prototype.
This is how prototypical (prototypal?) inheritance is done in JavaScript.
From MDN:
Refers to the prototype of the object, which may be an object or null
(which usually means the object is Object.prototype, which has no
prototype). It is sometimes used to implement prototype-inheritance
based property lookup.
This works as well:
var Emitter = function(obj) {
this.obj = obj;
}
// DON'T Emitter.prototype = new require('events').EventEmitter();
Emitter.prototype = Object.create(require('events').EventEmitter.prototype);
Understanding JavaScript OOP is one of the best articles I read lately on OOP in ECMAScript 5.
I thought this approach from http://www.bennadel.com/blog/2187-Extending-EventEmitter-To-Create-An-Evented-Cache-In-Node-js.htm was pretty neat:
function EventedObject(){
// Super constructor
EventEmitter.call( this );
return( this );
}
Douglas Crockford has some interesting inheritence patterns too: http://www.crockford.com/javascript/inheritance.html
I find inheritence is less often needed in JavaScript and Node.js. But in writing an app where inheritence might affect scalability, I would consider performance weighed against maintainability. Otherwise, I would only base my decision on which patterns lead to better overall designs, are more maintainable, and less error-prone.
Test different patterns out in jsPerf, using Google Chrome (V8) to get a rough comparison. V8 is the JavaScript engine used by both Node.js and Chrome.
Here're some jsPerfs to get you started:
http://jsperf.com/prototypes-vs-functions/4
http://jsperf.com/inheritance-proto-vs-object-create
http://jsperf.com/inheritance-perf
To add to wprl's response. He missed the "prototype" part:
function EventedObject(){
// Super constructor
EventEmitter.call(this);
return this;
}
EventObject.prototype = new EventEmitter(); //<-- you're missing this part

Resources