Browse By

Request Wikipedia API with NodeJs and RX Observables

RX_observables_NodejsReactiveX is one of those things that if you start using it then there is no turn back. RX observables gives you freedom and control at the same time. Below is a small code example on how to create an observable and subscribe to it. To observe a nodejs module like the request you have to pass it to fromNodeCallback. So here I am making a request with a search term to wikipedia API and expecting the first text paragraph.

NodeJS _RxJS_observable

var request = require('request'),
  Rx = require('rx');
  module.exports = function (app) {
    app.get("/", function (req, res) {
      if (!req.query.wiki) {
        return res.send({
          "status": "error",
          "message": "missing request info"
        });
      } else {
        var wikiReq = Rx.Observable.fromNodeCallback(request.get),
          call = wikiReq([
            'https://en.wikipedia.org/w/api.php',
            '?action=query',
            '&prop=extracts',
            '&format=json',
            '&exintro=1',
            '&explaintext=',
            '&titles=',
            req.query.wiki].join('')),
          subscription = call
            .subscribe(
            (wikiRes) => {
              return res.send(
                JSON.parse(wikiRes[1]).query.pages[
                  Object.keys(JSON.parse(wikiRes[1]).query.pages)[0]
                ].extract);
            },
            (err) => {
              console.log('Error: ' + err);
            },
            () => {
              console.log('Completed');
            });
      }
    });
  }

You can find the code in this github repository

Leave a Reply

Your email address will not be published. Required fields are marked *