source: trip-planner-front/node_modules/sockjs-client/lib/transport/receiver/xhr.js@ 76712b2

Last change on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.5 KB
Line 
1'use strict';
2
3var inherits = require('inherits')
4 , EventEmitter = require('events').EventEmitter
5 ;
6
7var debug = function() {};
8if (process.env.NODE_ENV !== 'production') {
9 debug = require('debug')('sockjs-client:receiver:xhr');
10}
11
12function XhrReceiver(url, AjaxObject) {
13 debug(url);
14 EventEmitter.call(this);
15 var self = this;
16
17 this.bufferPosition = 0;
18
19 this.xo = new AjaxObject('POST', url, null);
20 this.xo.on('chunk', this._chunkHandler.bind(this));
21 this.xo.once('finish', function(status, text) {
22 debug('finish', status, text);
23 self._chunkHandler(status, text);
24 self.xo = null;
25 var reason = status === 200 ? 'network' : 'permanent';
26 debug('close', reason);
27 self.emit('close', null, reason);
28 self._cleanup();
29 });
30}
31
32inherits(XhrReceiver, EventEmitter);
33
34XhrReceiver.prototype._chunkHandler = function(status, text) {
35 debug('_chunkHandler', status);
36 if (status !== 200 || !text) {
37 return;
38 }
39
40 for (var idx = -1; ; this.bufferPosition += idx + 1) {
41 var buf = text.slice(this.bufferPosition);
42 idx = buf.indexOf('\n');
43 if (idx === -1) {
44 break;
45 }
46 var msg = buf.slice(0, idx);
47 if (msg) {
48 debug('message', msg);
49 this.emit('message', msg);
50 }
51 }
52};
53
54XhrReceiver.prototype._cleanup = function() {
55 debug('_cleanup');
56 this.removeAllListeners();
57};
58
59XhrReceiver.prototype.abort = function() {
60 debug('abort');
61 if (this.xo) {
62 this.xo.close();
63 debug('close');
64 this.emit('close', null, 'user');
65 this.xo = null;
66 }
67 this._cleanup();
68};
69
70module.exports = XhrReceiver;
Note: See TracBrowser for help on using the repository browser.