rabbitmq-client
Version:
Robust, typed, RabbitMQ (0-9-1) client library
96 lines (95 loc) • 3.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = normalizeOptions;
const DEFAULT_CONNECTION = 'amqp://guest:guest@localhost:5672';
const TLS_PORT = '5671';
const TCP_PORT = '5672';
const DEFAULT_OPTS = {
acquireTimeout: 20000,
connectionTimeout: 10000,
frameMax: 8192,
heartbeat: 60,
maxChannels: 0x07ff, // (16bit number so the protocol max is 0xffff)
retryLow: 1000,
retryHigh: 30000,
};
/** @internal */
function normalizeOptions(raw) {
if (typeof raw === 'string') {
raw = { url: raw };
}
const props = { ...DEFAULT_OPTS, ...raw };
let url;
if (typeof props.url == 'string') {
url = new URL(props.url);
props.username = decodeURIComponent(url.username);
props.password = decodeURIComponent(url.password);
props.vhost = decodeURIComponent(url.pathname.split('/')[1] || '/');
props.hostname = url.hostname;
if (url.protocol === 'amqp:') {
props.port = url.port || TCP_PORT;
}
else if (url.protocol === 'amqps:') {
props.port = url.port || TLS_PORT;
props.tls = props.tls || true;
}
else {
throw new Error('unsupported protocol in connectionString; expected amqp: or amqps:');
}
const heartbeat = parseInt(url.searchParams.get('heartbeat'));
if (!isNaN(heartbeat)) {
props.heartbeat = Math.max(0, heartbeat);
}
const connectionTimeout = parseInt(url.searchParams.get('connection_timeout'));
if (!isNaN(connectionTimeout)) {
props.connectionTimeout = Math.max(0, connectionTimeout);
}
const maxChannels = parseInt(url.searchParams.get('channel_max'));
if (!isNaN(maxChannels)) {
props.maxChannels = Math.min(Math.max(1, maxChannels), props.maxChannels);
}
}
else {
url = new URL(DEFAULT_CONNECTION);
if (props.hostname == null)
props.hostname = url.hostname;
if (props.port == null)
props.port = url.port;
if (props.username == null)
props.username = url.username;
if (props.password == null)
props.password = url.password;
if (props.vhost == null)
props.vhost = '/';
}
if (props.tls === true)
props.tls = {};
if (Array.isArray(props.hosts)) {
props.hosts = props.hosts.map((host) => {
let [hostname, port] = host.split(':');
if (!port) {
port = props.tls ? TLS_PORT : TCP_PORT;
}
return { hostname, port };
});
}
else {
props.hosts = [{ hostname: props.hostname, port: props.port }];
}
assertNumber(props, 'acquireTimeout', 0);
assertNumber(props, 'connectionTimeout', 0);
assertNumber(props, 'frameMax', 8, 2 ** 32 - 1);
assertNumber(props, 'heartbeat', 0);
assertNumber(props, 'maxChannels', 1, 2 ** 16 - 1);
assertNumber(props, 'retryLow', 1);
assertNumber(props, 'retryHigh', 1);
return props;
}
function assertNumber(props, name, min, max) {
const val = props[name];
if (isNaN(val) || !Number.isFinite(val) || val < min || (max != null && val > max)) {
throw new TypeError(max != null
? `${name} must be a number (${min}, ${max})`
: `${name} must be a number >= ${min}`);
}
}