UNPKG

2.75 kBJavaScriptView Raw
1module.exports = ConnectionAbstract;
2
3var _ = require('lodash');
4var utils = require('./utils');
5var EventEmitter = require('events').EventEmitter;
6var Log = require('./log');
7var Host = require('./host');
8var errors = require('./errors');
9
10/**
11 * Abstract class used for Connection classes
12 * @class ConnectionAbstract
13 * @constructor
14 */
15function ConnectionAbstract(host, config) {
16 config = config || {};
17 EventEmitter.call(this);
18
19 this.log = config.log || new Log();
20 this.pingTimeout = config.pingTimeout || 3000;
21
22 if (!host) {
23 throw new TypeError('Missing host');
24 } else if (host instanceof Host) {
25 this.host = host;
26 } else {
27 throw new TypeError('Invalid host');
28 }
29
30 utils.makeBoundMethods(this);
31}
32utils.inherits(ConnectionAbstract, EventEmitter);
33
34/**
35 * Make a request using this connection. Must be overridden by Connection classes, which can add whatever keys to
36 * params that they like. These are just the basics.
37 *
38 * @param [params] {Object} - The parameters for the request
39 * @param params.path {String} - The path for which you are requesting
40 * @param params.method {String} - The HTTP method for the request (GET, HEAD, etc.)
41 * @param params.requestTimeout {Integer} - The amount of time in milliseconds that this request should be allowed to run for.
42 * @param cb {Function} - A callback to be called once with `cb(err, responseBody, responseStatus)`
43 */
44ConnectionAbstract.prototype.request = function() {
45 throw new Error('Connection#request must be overwritten by the Connector');
46};
47
48ConnectionAbstract.prototype.ping = function(params, cb) {
49 if (typeof params === 'function') {
50 cb = params;
51 params = null;
52 } else {
53 cb = typeof cb === 'function' ? cb : null;
54 }
55
56 var requestTimeout = this.pingTimeout;
57 var requestTimeoutId;
58 var aborted;
59 var abort;
60
61 if (params && params.hasOwnProperty('requestTimeout')) {
62 requestTimeout = params.requestTimeout;
63 }
64
65 abort = this.request(
66 _.defaults(params || {}, {
67 path: '/',
68 method: 'HEAD',
69 }),
70 function(err) {
71 if (aborted) {
72 return;
73 }
74 clearTimeout(requestTimeoutId);
75 if (cb) {
76 cb(err);
77 }
78 }
79 );
80
81 if (requestTimeout) {
82 requestTimeoutId = setTimeout(function() {
83 if (abort) {
84 abort();
85 }
86 aborted = true;
87 if (cb) {
88 cb(
89 new errors.RequestTimeout(
90 'Ping Timeout after ' + requestTimeout + 'ms'
91 )
92 );
93 }
94 }, requestTimeout);
95 }
96};
97
98ConnectionAbstract.prototype.setStatus = function(status) {
99 var origStatus = this.status;
100 this.status = status;
101
102 this.emit('status set', status, origStatus, this);
103
104 if (status === 'closed') {
105 this.removeAllListeners();
106 }
107};