client.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2015 rain1017.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. // implied. See the License for the specific language governing
  13. // permissions and limitations under the License. See the AUTHORS file
  14. // for names of contributors.
  15. 'use strict';
  16. var util = require('util');
  17. var logger = require('memdb-client').logger.getLogger('test', __filename);
  18. var P = require('memdb-client').Promise;
  19. var pomeloClient = require('./pomelo-client');
  20. var Client = function(opts){
  21. opts = opts || {};
  22. this.client = pomeloClient();
  23. this.opts = opts;
  24. };
  25. var proto = Client.prototype;
  26. var connects = 0;
  27. proto.connect = function(){
  28. var self = this;
  29. return new P(function(resolve, reject){
  30. self.client.init(self.opts, function(data){
  31. if(!!data){
  32. connects += 1;
  33. logger.info('connected to %s:%s', self.opts.host, self.opts.port, ' connects: ', connects);
  34. resolve(data);
  35. }
  36. else{
  37. reject(new Error('connect failed'));
  38. }
  39. });
  40. });
  41. };
  42. proto.disconnect = function(){
  43. this.client.disconnect();
  44. logger.info('disconnect from %s:%s', this.opts.host, this.opts.port);
  45. };
  46. var sends = 0;
  47. proto.request = function(route, msg){
  48. msg = msg || {};
  49. var self = this;
  50. return new P(function(resolve, reject){
  51. logger.info('request %s %j', route, msg);
  52. self.client.request(route, msg, function(ret){
  53. if(ret.code === 500){
  54. logger.error('response %j', ret);
  55. reject(ret);
  56. }
  57. else{
  58. sends += 1;
  59. logger.info('response %j', ret, 'sends: ', sends);
  60. resolve(ret);
  61. }
  62. });
  63. });
  64. };
  65. proto.notify = function(route, msg){
  66. logger.info('notify %s %j', route, msg);
  67. this.client.notify(route, msg);
  68. };
  69. proto.on = function(route, fn){
  70. this.client.on(route, function(msg){
  71. logger.info('on %s: %j', route, msg);
  72. fn.apply(null, arguments);
  73. });
  74. };
  75. module.exports = function(opts){
  76. return new Client(opts);
  77. };