Search code examples
node.jsrestpush-notificationchatobserver-pattern

Is it possible to implement observer pattern using REST API


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.


Solution

  • 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