Search code examples
javascriptgun

How to get multiple nodes by single request?


gun 0.8.8

Is it possible to get multiple nodes by single get request?

For example, something like this

gun.mget([ "nodeNameA", "nodeNameB" ], function(value) 
  console.log(value);
  /*
    {
      "nodeNameA": { my: "Special", variable: 123 },
      "nodeNameB": { the: "Glory", answer: 42 }
    }
  */
  // ... do something ...
});

In many databases, you can get multiple objects by a single query. Due to the network latency sometimes it is faster to get a single response instead of hundreds of small ones.


Solution

  • @trex ,

    Using the extended API .open(cb) on a table is probably what you want.

    Here is an example:

    var gun = Gun();
    
    gun.get('nodeNameA').put({ my: "Special", variable: 123 });
    gun.get('table').set(gun.get('nodeNameA'));
    
    
    gun.get('nodeNameB').put({ the: "Glory", answer: 42 });
    gun.get('table').set(gun.get('nodeNameB'));
    
    
    gun.get('table').open(function(data, key){
      console.log("update:", data);
      /*
        {
          "nodeNameA": { my: "Special", variable: 123 },
          "nodeNameB": { the: "Glory", answer: 42 }
        }
      */
    });
    

    Play with it yourself here: http://jsbin.com/ditohivovo/edit?js,console !

    Documentation is available here:

    https://github.com/amark/gun/wiki/API#open

    Note: You must include it with require('lib/open.js') or <script src="gun/lib/open.js"></script> in the browser.