@znode/influx
Version:
Node.js Influx Client
114 lines (113 loc) • 3.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.InfluxURI = void 0;
const url_1 = require("url");
const auth = require("./auth");
class InfluxURI {
constructor(options) {
this.options = options;
this._uri = null;
this._query = null;
if (options.uri) {
this._uri = new url_1.URL(options.uri);
if (this._uri.search) {
this._query = new URLSearchParams(this._uri.search);
}
}
}
get host() {
var _a;
const { options } = this;
const host = options.host || ((_a = this._uri) === null || _a === void 0 ? void 0 : _a.hostname);
if (!host) {
throw new Error(`host is required`);
}
return host;
}
get port() {
const { options, _uri } = this;
let port = options.port || (_uri === null || _uri === void 0 ? void 0 : _uri.port);
if (!port) {
if (!_uri) {
throw new Error(`port is required`);
}
if (_uri.protocol === 'http:') {
port = 80;
}
else if (_uri.protocol === 'https:') {
port = 443;
}
else if (_uri.protocol === 'influx:') {
port = 443;
}
else {
throw new Error(`unknown protocol: ${_uri.protocol}`);
}
}
return port;
}
get database() {
var _a, _b;
const { options } = this;
const database = options.database ||
((_a = this._query) === null || _a === void 0 ? void 0 : _a.get('db')) ||
((_b = this._query) === null || _b === void 0 ? void 0 : _b.get('database'));
if (!database) {
if (!options.uri) {
throw new Error(`database options is required`);
}
throw new Error(`db search is required, but missing (uri: ${this.options.uri})`);
}
return database;
}
get username() {
var _a;
const { options } = this;
const username = options.username || ((_a = this._uri) === null || _a === void 0 ? void 0 : _a.username);
if (!username) {
throw new Error(`username is required`);
}
return username;
}
get password() {
var _a;
const { options } = this;
const password = options.password || ((_a = this._uri) === null || _a === void 0 ? void 0 : _a.password);
if (!password) {
throw new Error(`password is required`);
}
return password;
}
get server() {
const { host, port } = this;
return `${host}:${port}`;
}
uri(actionType) {
const { secure } = this.options;
const { host, port, database } = this;
const isSecure = port === 443 || secure;
const protocol = isSecure ? 'https' : 'http';
// if (username && password) {
// return `${protocol}://${username}:${password}@${host}:${port}/${actionType}?db=${database}`;
// }
if (port === 443 || port === 80) {
return `${protocol}://${host}/${actionType}?db=${database}`;
}
return `${protocol}://${host}:${port}/${actionType}?db=${database}`;
}
get query() {
return this.uri('query');
}
get write() {
return this.uri('write');
}
get headers() {
const { username, password } = this;
const headers = {};
if (username && password) {
headers['Authorization'] = auth.buildBasicAuthorization(username, password);
}
return headers;
}
}
exports.InfluxURI = InfluxURI;