info-ajax.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. var EventEmitter = require('events').EventEmitter
  3. , inherits = require('inherits')
  4. , JSON3 = require('json3')
  5. , objectUtils = require('./utils/object')
  6. ;
  7. var debug = function() {};
  8. if (process.env.NODE_ENV !== 'production') {
  9. debug = require('debug')('sockjs-client:info-ajax');
  10. }
  11. function InfoAjax(url, AjaxObject) {
  12. EventEmitter.call(this);
  13. var self = this;
  14. var t0 = +new Date();
  15. this.xo = new AjaxObject('GET', url);
  16. this.xo.once('finish', function(status, text) {
  17. var info, rtt;
  18. if (status === 200) {
  19. rtt = (+new Date()) - t0;
  20. if (text) {
  21. try {
  22. info = JSON3.parse(text);
  23. } catch (e) {
  24. debug('bad json', text);
  25. }
  26. }
  27. if (!objectUtils.isObject(info)) {
  28. info = {};
  29. }
  30. }
  31. self.emit('finish', info, rtt);
  32. self.removeAllListeners();
  33. });
  34. }
  35. inherits(InfoAjax, EventEmitter);
  36. InfoAjax.prototype.close = function() {
  37. this.removeAllListeners();
  38. this.xo.close();
  39. };
  40. module.exports = InfoAjax;