/
ConnectionStringParser.js
96 lines (80 loc) · 2.33 KB
/
ConnectionStringParser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Copyright (c) 2013 Yahoo! Inc. All rights reserved.
*
* Copyrights licensed under the MIT License. See the accompanying LICENSE file
* for terms.
*/
var assert = require('assert');
var u = require('underscore');
var Path = require('./Path.js');
// Constants.
var DEFAULT_PORT = 2181; // Default Zookeeper client port.
/**
* This class parse the connection string to build the ensemble server
* list and chrootPath.
*
* @module node-zookeeper-client
*/
/**
*
* Parse the connect string and random the servers of the ensemble.
*
* @module node-zookeeper-client
* @class ConnectionStringParser
* @constructor
* @param connectionString {String} ZooKeeper server ensemble string.
*/
function ConnectionStringParser(connectionString) {
assert(
connectionString && typeof connectionString === 'string',
'connectionString must be a non-empty string.'
);
this.connectionString = connectionString;
// Handle chroot
var index = connectionString.indexOf('/'),
hostList = [],
servers = [];
if (index !== -1 && index !== (connectionString.length - 1)) {
this.chrootPath = connectionString.substring(index);
Path.validate(this.chrootPath);
} else {
this.chrootPath = undefined;
}
if (index !== -1) {
hostList = connectionString.substring(0, index).split(',');
} else {
hostList = connectionString.split(',');
}
hostList.filter(function (item) {
// Filter out empty string.
return item;
}).forEach(function (item) {
var parts = item.split(':');
servers.push({
host : parts[0],
port : parts[1] || DEFAULT_PORT
});
});
assert(
servers.length > 0,
'connectionString must contain at least one server.'
);
// Randomize the list.
this.servers = u.shuffle(servers);
}
/**
* Return the connection string of this host provider.
*
* @method getConnectionString
* @return The connection string.
*/
ConnectionStringParser.prototype.getConnectionString = function () {
return this.connectionString;
};
ConnectionStringParser.prototype.getChrootPath = function () {
return this.chrootPath;
};
ConnectionStringParser.prototype.getServers = function () {
return this.servers.slice(0);
};
module.exports = ConnectionStringParser;