client.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * Expose `Client`.
  3. */
  4. module.exports = Client;
  5. /**
  6. * Initialize an rpc client with `sock`.
  7. *
  8. * @param {Socket} sock
  9. * @api public
  10. */
  11. function Client(sock) {
  12. if (typeof sock.format === 'function') sock.format('json');
  13. this.sock = sock;
  14. }
  15. /**
  16. * Invoke method `name` with args and invoke the
  17. * tailing callback function.
  18. *
  19. * @param {String} name
  20. * @param {Mixed} ...
  21. * @param {Function} fn
  22. * @api public
  23. */
  24. Client.prototype.call = function(name){
  25. var args = [].slice.call(arguments, 1, -1);
  26. var fn = arguments[arguments.length - 1];
  27. this.sock.send({
  28. type: 'call',
  29. method: name,
  30. args: args
  31. }, function(msg){
  32. if ('error' in msg) {
  33. var err = new Error(msg.error);
  34. err.stack = msg.stack || err.stack;
  35. fn(err);
  36. } else {
  37. msg.args.unshift(null);
  38. fn.apply(null, msg.args);
  39. }
  40. });
  41. };
  42. /**
  43. * Fetch the methods exposed and invoke `fn(err, methods)`.
  44. *
  45. * @param {Function} fn
  46. * @api public
  47. */
  48. Client.prototype.methods = function(fn){
  49. this.sock.send({
  50. type: 'methods'
  51. }, function(msg){
  52. fn(null, msg.methods);
  53. });
  54. };