influx 5.0.6 → 5.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/src/index.js CHANGED
@@ -1,870 +1,870 @@
1
- "use strict";
2
- function __export(m) {
3
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
- }
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- var url = require("url");
7
- var b = require("./builder");
8
- var grammar = require("./grammar");
9
- var pool_1 = require("./pool");
10
- var results_1 = require("./results");
11
- var schema_1 = require("./schema");
12
- var defaultHost = Object.freeze({
13
- host: '127.0.0.1',
14
- port: 8086,
15
- protocol: 'http',
16
- });
17
- var defaultOptions = Object.freeze({
18
- database: null,
19
- hosts: [],
20
- password: 'root',
21
- schema: [],
22
- username: 'root',
23
- });
24
- __export(require("./builder"));
25
- var grammar_1 = require("./grammar");
26
- exports.FieldType = grammar_1.FieldType;
27
- exports.Precision = grammar_1.Precision;
28
- exports.Raw = grammar_1.Raw;
29
- exports.escape = grammar_1.escape;
30
- exports.toNanoDate = grammar_1.toNanoDate;
31
- var results_2 = require("./results");
32
- exports.ResultError = results_2.ResultError;
33
- /**
34
- * Parses the URL out into into a IClusterConfig object
35
- */
36
- function parseOptionsUrl(addr) {
37
- var parsed = url.parse(addr);
38
- var options = {
39
- host: parsed.hostname,
40
- port: Number(parsed.port),
41
- protocol: parsed.protocol.slice(0, -1),
42
- };
43
- if (parsed.auth) {
44
- _a = parsed.auth.split(':'), options.username = _a[0], options.password = _a[1];
45
- }
46
- if (parsed.pathname.length > 1) {
47
- options.database = parsed.pathname.slice(1);
48
- }
49
- return options;
50
- var _a;
51
- }
52
- /**
53
- * Works similarly to Object.assign, but only overwrites
54
- * properties that resolve to undefined.
55
- */
56
- function defaults(target) {
57
- var srcs = [];
58
- for (var _i = 1; _i < arguments.length; _i++) {
59
- srcs[_i - 1] = arguments[_i];
60
- }
61
- srcs.forEach(function (src) {
62
- Object.keys(src).forEach(function (key) {
63
- if (target[key] === undefined) {
64
- target[key] = src[key];
65
- }
66
- });
67
- });
68
- return target;
69
- }
70
- /**
71
- * InfluxDB is the public interface to run queries against the your database.
72
- * This is a 'driver-level' module, not a a full-fleged ORM or ODM; you run
73
- * queries directly by calling methods on this class.
74
- *
75
- * Please check out some of [the tutorials](https://node-influx.github.io/manual/tutorial.html)
76
- * if you want help getting started!
77
- *
78
- * @example
79
- * const Influx = require('influx');
80
- * const influx = new Influx.InfluxDB({
81
- * host: 'localhost',
82
- * database: 'express_response_db',
83
- * schema: [
84
- * {
85
- * measurement: 'response_times',
86
- * fields: {
87
- * path: Influx.FieldType.STRING,
88
- * duration: Influx.FieldType.INTEGER
89
- * },
90
- * tags: [
91
- * 'host'
92
- * ]
93
- * }
94
- * ]
95
- * })
96
- *
97
- * influx.writePoints([
98
- * {
99
- * measurement: 'response_times',
100
- * tags: { host: os.hostname() },
101
- * fields: { duration, path: req.path },
102
- * }
103
- * ]).then(() => {
104
- * return influx.query(`
105
- * select * from response_times
106
- * where host = ${Influx.escape.stringLit(os.hostname())}
107
- * order by time desc
108
- * limit 10
109
- * `)
110
- * }).then(rows => {
111
- * rows.forEach(row => console.log(`A request to ${row.path} took ${row.duration}ms`))
112
- * })
113
- */
114
- var InfluxDB = (function () {
115
- /**
116
- * Connect to a single InfluxDB instance by specifying
117
- * a set of connection options.
118
- * @param {IClusterConfig|ISingleHostConfig|string} [options='http://root:root@127.0.0.1:8086']
119
- *
120
- * @example
121
- * const Influx = require('influx')
122
- *
123
- * // Connect to a single host with a DSN:
124
- * const influx = new Influx.InfluxDB('http://user:password@host:8086/database')
125
- *
126
- * @example
127
- * const Influx = require('influx')
128
- *
129
- * // Connect to a single host with a full set of config details and
130
- * // a custom schema
131
- * const client = new Influx.InfluxDB({
132
- * database: 'my_db',
133
- * host: 'localhost',
134
- * port: 8086,
135
- * username: 'connor',
136
- * password: 'pa$$w0rd',
137
- * schema: [
138
- * {
139
- * measurement: 'perf',
140
- * fields: {
141
- * memory_usage: Influx.FieldType.INTEGER,
142
- * cpu_usage: Influx.FieldType.FLOAT,
143
- * is_online: Influx.FieldType.BOOLEAN
144
- * }
145
- * tags: [
146
- * 'hostname'
147
- * ]
148
- * }
149
- * ]
150
- * })
151
- *
152
- * @example
153
- * const Influx = require('influx')
154
- *
155
- * // Use a pool of several host connections and balance queries across them:
156
- * const client = new Influx.InfluxDB({
157
- * database: 'my_db',
158
- * username: 'connor',
159
- * password: 'pa$$w0rd',
160
- * hosts: [
161
- * { host: 'db1.example.com' },
162
- * { host: 'db2.example.com' },
163
- * ],
164
- * schema: [
165
- * {
166
- * measurement: 'perf',
167
- * fields: {
168
- * memory_usage: Influx.FieldType.INTEGER,
169
- * cpu_usage: Influx.FieldType.FLOAT,
170
- * is_online: Influx.FieldType.BOOLEAN
171
- * }
172
- * tags: [
173
- * 'hostname'
174
- * ]
175
- * }
176
- * ]
177
- * })
178
- *
179
- */
180
- function InfluxDB(options) {
181
- var _this = this;
182
- /**
183
- * Map of Schema instances defining measurements in Influx.
184
- * @private
185
- */
186
- this.schema = Object.create(null);
187
- // Figure out how to parse whatever we were passed in into a IClusterConfig.
188
- if (typeof options === 'string') {
189
- options = parseOptionsUrl(options);
190
- }
191
- else if (!options) {
192
- options = defaultHost;
193
- }
194
- if (!options.hasOwnProperty('hosts')) {
195
- options = {
196
- database: options.database,
197
- hosts: [options],
198
- password: options.password,
199
- pool: options.pool,
200
- schema: options.schema,
201
- username: options.username,
202
- };
203
- }
204
- var resolved = options;
205
- resolved.hosts = resolved.hosts.map(function (host) {
206
- return defaults({
207
- host: host.host,
208
- port: host.port,
209
- protocol: host.protocol,
210
- options: host.options,
211
- }, defaultHost);
212
- });
213
- this.pool = new pool_1.Pool(resolved.pool);
214
- this.options = defaults(resolved, defaultOptions);
215
- resolved.hosts.forEach(function (host) {
216
- _this.pool.addHost(host.protocol + "://" + host.host + ":" + host.port, host.options);
217
- });
218
- this.options.schema.forEach(function (schema) {
219
- var db = schema.database = schema.database || _this.options.database;
220
- if (!db) {
221
- throw new Error("Schema " + schema.measurement + " doesn't have a database specified," +
222
- 'and no default database is provided!');
223
- }
224
- if (!_this.schema[db]) {
225
- _this.schema[db] = Object.create(null);
226
- }
227
- _this.schema[db][schema.measurement] = new schema_1.Schema(schema);
228
- });
229
- }
230
- /**
231
- * Creates a new database with the provided name.
232
- * @param {string} databaseName
233
- * @return {Promise.<void>}
234
- * @example
235
- * influx.createDatabase('mydb')
236
- */
237
- InfluxDB.prototype.createDatabase = function (databaseName) {
238
- return this.pool.json(this.getQueryOpts({
239
- q: "create database " + grammar.escape.quoted(databaseName),
240
- }, 'POST')).then(results_1.assertNoErrors);
241
- };
242
- /**
243
- * Deletes a database with the provided name.
244
- * @param {string} databaseName
245
- * @return {Promise.<void>}
246
- * @example
247
- * influx.createDatabase('mydb')
248
- */
249
- InfluxDB.prototype.dropDatabase = function (databaseName) {
250
- return this.pool.json(this.getQueryOpts({
251
- q: "drop database " + grammar.escape.quoted(databaseName),
252
- }, 'POST')).then(results_1.assertNoErrors);
253
- };
254
- /**
255
- * Returns array of database names. Requires cluster admin privileges.
256
- * @returns {Promise<String[]>} a list of database names
257
- * @example
258
- * influx.getMeasurements().then(names =>
259
- * console.log('My database names are: ' + names.join(', ')));
260
- */
261
- InfluxDB.prototype.getDatabaseNames = function () {
262
- return this.pool.json(this.getQueryOpts({ q: 'show databases' }))
263
- .then(function (res) { return results_1.parseSingle(res).map(function (r) { return r.name; }); });
264
- };
265
- /**
266
- * Returns array of measurements.
267
- * @returns {Promise<String[]>} a list of measurement names
268
- * @param {String} [database] the database the measurement lives in, optional
269
- * if a default database is provided.
270
- * @example
271
- * influx.getMeasurements().then(names =>
272
- * console.log('My measurement names are: ' + names.join(', ')));
273
- */
274
- InfluxDB.prototype.getMeasurements = function (database) {
275
- if (database === void 0) { database = this.defaultDB(); }
276
- return this.pool.json(this.getQueryOpts({
277
- db: database,
278
- q: 'show measurements',
279
- })).then(function (res) { return results_1.parseSingle(res).map(function (r) { return r.name; }); });
280
- };
281
- /**
282
- * Returns a list of all series within the target measurement, or from the
283
- * entire database if a measurement isn't provided.
284
- * @param {Object} [options]
285
- * @param {String} [options.measurement] if provided, we'll only get series
286
- * from within that measurement.
287
- * @param {String} [options.database] the database the series lives in,
288
- * optional if a default database is provided.
289
- * @returns {Promise<String[]>} a list of series names
290
- * @example
291
- * influx.getSeries().then(names => {
292
- * console.log('My series names in my_measurement are: ' + names.join(', '))
293
- * })
294
- *
295
- * influx.getSeries({
296
- * measurement: 'my_measurement',
297
- * database: 'my_db'
298
- * }).then(names => {
299
- * console.log('My series names in my_measurement are: ' + names.join(', '))
300
- * })
301
- */
302
- InfluxDB.prototype.getSeries = function (options) {
303
- if (options === void 0) { options = {}; }
304
- var _a = options.database, database = _a === void 0 ? this.defaultDB() : _a, measurement = options.measurement;
305
- var query = 'show series';
306
- if (measurement) {
307
- query += " from " + grammar.escape.quoted(measurement);
308
- }
309
- return this.pool.json(this.getQueryOpts({
310
- db: database,
311
- q: query,
312
- })).then(function (res) { return results_1.parseSingle(res).map(function (r) { return r.key; }); });
313
- };
314
- /**
315
- * Removes a measurement from the database.
316
- * @param {String} measurement
317
- * @param {String} [database] the database the measurement lives in, optional
318
- * if a default database is provided.
319
- * @return {Promise.<void>}
320
- * @example
321
- * influx.dropMeasurement('my_measurement')
322
- */
323
- InfluxDB.prototype.dropMeasurement = function (measurement, database) {
324
- if (database === void 0) { database = this.defaultDB(); }
325
- return this.pool.json(this.getQueryOpts({
326
- db: database,
327
- q: "drop measurement " + grammar.escape.quoted(measurement),
328
- }, 'POST')).then(results_1.assertNoErrors);
329
- };
330
- /**
331
- * Removes a one or more series from InfluxDB.
332
- *
333
- * @returns {Promise<void>}
334
- * @example
335
- * // The following pairs of queries are equivalent: you can chose either to
336
- * // use our builder or pass in string directly. The builder takes care
337
- * // of escaping and most syntax handling for you.
338
- *
339
- * influx.dropSeries({ where: e => e.tag('cpu').equals.value('cpu8') })
340
- * influx.dropSeries({ where: '"cpu" = \'cpu8\'' })
341
- * // DROP SERIES WHERE "cpu" = 'cpu8'
342
- *
343
- * influx.dropSeries({ measurement: m => m.name('cpu').policy('autogen') })
344
- * influx.dropSeries({ measurement: '"cpu"."autogen"' })
345
- * // DROP SERIES FROM "autogen"."cpu"
346
- *
347
- * influx.dropSeries({
348
- * measurement: m => m.name('cpu').policy('autogen'),
349
- * where: e => e.tag('cpu').equals.value('cpu8'),
350
- * database: 'my_db'
351
- * })
352
- * // DROP SERIES FROM "autogen"."cpu" WHERE "cpu" = 'cpu8'
353
- */
354
- InfluxDB.prototype.dropSeries = function (options) {
355
- var db = 'database' in options ? options.database : this.defaultDB();
356
- var q = 'drop series';
357
- if ('measurement' in options) {
358
- q += ' from ' + b.parseMeasurement(options);
359
- }
360
- if ('where' in options) {
361
- q += ' where ' + b.parseWhere(options);
362
- }
363
- return this.pool.json(this.getQueryOpts({ db: db, q: q }, 'POST')).then(results_1.assertNoErrors);
364
- };
365
- /**
366
- * Returns a list of users on the Influx database.
367
- * @return {Promise<Array<{ user: String, admin: Boolean }>>}
368
- * @example
369
- * influx.getUsers().then(users => {
370
- * users.forEach(user => {
371
- * if (user.admin) {
372
- * console.log(user.user, 'is an admin!')
373
- * } else {
374
- * console.log(user.user, 'is not an admin!')
375
- * }
376
- * })
377
- * })
378
- */
379
- InfluxDB.prototype.getUsers = function () {
380
- return this.pool.json(this.getQueryOpts({ q: 'show users' })).then(results_1.parseSingle);
381
- };
382
- /**
383
- * Creates a new InfluxDB user.
384
- * @param {String} username
385
- * @param {String} password
386
- * @param {Boolean} [admin=false] If true, the user will be given all
387
- * privileges on all databases.
388
- * @return {Promise<void>}
389
- * @example
390
- * influx.createUser('connor', 'pa55w0rd', true) // make 'connor' an admin
391
- *
392
- * // make non-admins:
393
- * influx.createUser('not_admin', 'pa55w0rd')
394
- */
395
- InfluxDB.prototype.createUser = function (username, password, admin) {
396
- if (admin === void 0) { admin = false; }
397
- return this.pool.json(this.getQueryOpts({
398
- q: "create user " + grammar.escape.quoted(username) + " with password "
399
- + grammar.escape.stringLit(password)
400
- + (admin ? ' with all privileges' : ''),
401
- }, 'POST')).then(results_1.assertNoErrors);
402
- };
403
- /**
404
- * Sets a password for an Influx user.
405
- * @param {String} username
406
- * @param {String} password
407
- * @return {Promise<void>}
408
- * @example
409
- * influx.setPassword('connor', 'pa55w0rd')
410
- */
411
- InfluxDB.prototype.setPassword = function (username, password) {
412
- return this.pool.json(this.getQueryOpts({
413
- q: "set password for " + grammar.escape.quoted(username) + " = "
414
- + grammar.escape.stringLit(password),
415
- }, 'POST')).then(results_1.assertNoErrors);
416
- };
417
- /**
418
- * Grants a privilege to a specified user.
419
- * @param {String} username
420
- * @param {String} privilege Should be one of 'READ' or 'WRITE'
421
- * @param {String} [database] If not provided, uses the default database.
422
- * @return {Promise<void>}
423
- * @example
424
- * influx.grantPrivilege('connor', 'READ', 'my_db') // grants read access on my_db to connor
425
- */
426
- InfluxDB.prototype.grantPrivilege = function (username, privilege, database) {
427
- if (database === void 0) { database = this.defaultDB(); }
428
- return this.pool.json(this.getQueryOpts({
429
- q: "grant " + privilege + " on " + grammar.escape.quoted(database) + " "
430
- + ("to " + grammar.escape.quoted(username)),
431
- }, 'POST')).then(results_1.assertNoErrors);
432
- };
433
- /**
434
- * Removes a privilege from a specified user.
435
- * @param {String} username
436
- * @param {String} privilege Should be one of 'READ' or 'WRITE'
437
- * @param {String} [database] If not provided, uses the default database.
438
- * @return {Promise<void>}
439
- * @example
440
- * influx.revokePrivilege('connor', 'READ', 'my_db') // removes read access on my_db from connor
441
- */
442
- InfluxDB.prototype.revokePrivilege = function (username, privilege, database) {
443
- if (database === void 0) { database = this.defaultDB(); }
444
- return this.pool.json(this.getQueryOpts({
445
- q: "revoke " + privilege + " from " + grammar.escape.quoted(username) + " on "
446
- + grammar.escape.quoted(database),
447
- }, 'POST')).then(results_1.assertNoErrors);
448
- };
449
- /**
450
- * Grants admin privileges to a specified user.
451
- * @param {String} username
452
- * @return {Promise<void>}
453
- * @example
454
- * influx.grantAdminPrivilege('connor')
455
- */
456
- InfluxDB.prototype.grantAdminPrivilege = function (username) {
457
- return this.pool.json(this.getQueryOpts({
458
- q: "grant all to " + grammar.escape.quoted(username),
459
- }, 'POST')).then(results_1.assertNoErrors);
460
- };
461
- /**
462
- * Removes a admin privilege from a specified user.
463
- * @param {String} username
464
- * @return {Promise<void>}
465
- * @example
466
- * influx.revokeAdminPrivilege('connor')
467
- */
468
- InfluxDB.prototype.revokeAdminPrivilege = function (username) {
469
- return this.pool.json(this.getQueryOpts({
470
- q: "revoke all from " + grammar.escape.quoted(username),
471
- }, 'POST')).then(results_1.assertNoErrors);
472
- };
473
- /**
474
- * Removes a user from the database.
475
- * @param {String} username
476
- * @return {Promise<void>}
477
- * @example
478
- * influx.dropUser('connor')
479
- */
480
- InfluxDB.prototype.dropUser = function (username) {
481
- return this.pool.json(this.getQueryOpts({
482
- q: "drop user " + grammar.escape.quoted(username),
483
- }, 'POST')).then(results_1.assertNoErrors);
484
- };
485
- /**
486
- * Creates a continuous query in a database
487
- * @param {String} name The query name, for later reference
488
- * @param {String} query The body of the query to run
489
- * @param {String} [database] If not provided, uses the default database.
490
- * @return {Promise<void>}
491
- * @example
492
- * influx.createContinuousQuery('downsample_cpu_1h', `
493
- * SELECT MEAN(cpu) INTO "7d"."perf"
494
- * FROM "1d"."perf" GROUP BY time(1m)
495
- * `)
496
- */
497
- InfluxDB.prototype.createContinuousQuery = function (name, query, database) {
498
- if (database === void 0) { database = this.defaultDB(); }
499
- return this.pool.json(this.getQueryOpts({
500
- q: "create continuous query " + grammar.escape.quoted(name)
501
- + (" on " + grammar.escape.quoted(database) + " begin " + query + " end"),
502
- }, 'POST')).then(results_1.assertNoErrors);
503
- };
504
- /**
505
- * Returns a list of continous queries in the database.
506
- * @param {String} [database] If not provided, uses the default database.
507
- * @return {Promise<void>}
508
- * @example
509
- * influx.showContinousQueries()
510
- */
511
- InfluxDB.prototype.showContinousQueries = function (database) {
512
- if (database === void 0) { database = this.defaultDB(); }
513
- return this.pool.json(this.getQueryOpts({
514
- db: database,
515
- q: 'show continuous queries',
516
- })).then(results_1.parseSingle);
517
- };
518
- /**
519
- * Creates a continuous query in a database
520
- * @param {String} name The query name
521
- * @param {String} [database] If not provided, uses the default database.
522
- * @return {Promise<void>}
523
- * @example
524
- * influx.dropContinuousQuery('downsample_cpu_1h')
525
- */
526
- InfluxDB.prototype.dropContinuousQuery = function (name, database) {
527
- if (database === void 0) { database = this.defaultDB(); }
528
- return this.pool.json(this.getQueryOpts({
529
- q: "drop continuous query " + grammar.escape.quoted(name)
530
- + (" on " + grammar.escape.quoted(database)),
531
- }, 'POST')).then(results_1.assertNoErrors);
532
- };
533
- /**
534
- * Creates a new retention policy on a database. You can read more about
535
- * [Downsampling and Retention](https://docs.influxdata.com/influxdb/v1.0/
536
- * guides/downsampling_and_retention/) on the InfluxDB website.
537
- *
538
- * @param {String} name The retention policy name
539
- * @param {Object} options
540
- * @param {String} [options.database] Database to create the policy on,
541
- * uses the default database if not provided.
542
- * @param {String} options.duration How long data in the retention policy
543
- * should be stored for, should be in a format like `7d`. See details
544
- * [here](https://docs.influxdata.com/influxdb/v1.0/query_language/spec/#durations)
545
- * @param {Number} options.replication How many servers data in the series
546
- * should be replicated to.
547
- * @param {Boolean} [options.isDefault] Whether the retention policy should
548
- * be the default policy on the database.
549
- * @return {Promise<void>}
550
- * @example
551
- * influx.createRetentionPolicy('7d', {
552
- * duration: '7d',
553
- * replication: 1
554
- * })
555
- */
556
- InfluxDB.prototype.createRetentionPolicy = function (name, options) {
557
- var q = "create retention policy " + grammar.escape.quoted(name) + " on "
558
- + grammar.escape.quoted(options.database || this.defaultDB())
559
- + (" duration " + options.duration + " replication " + options.replication)
560
- + (options.isDefault ? ' default' : '');
561
- return this.pool.json(this.getQueryOpts({ q: q }, 'POST')).then(results_1.assertNoErrors);
562
- };
563
- /**
564
- * Alters an existing retention policy on a database.
565
- *
566
- * @param {String} name The retention policy name
567
- * @param {Object} options
568
- * @param {String} [options.database] Database to create the policy on,
569
- * uses the default database if not provided.
570
- * @param {String} options.duration How long data in the retention policy
571
- * should be stored for, should be in a format like `7d`. See details
572
- * [here](https://docs.influxdata.com/influxdb/v1.0/query_language/spec/#durations)
573
- * @param {Number} options.replication How many servers data in the series
574
- * should be replicated to.
575
- * @param {Boolean} [options.default] Whether the retention policy should
576
- * be the default policy on the database.
577
- * @return {Promise<void>}
578
- * @example
579
- * influx.alterRetentionPolicy('7d', {
580
- * duration: '7d',
581
- * replication: 1,
582
- * default: true
583
- * })
584
- */
585
- InfluxDB.prototype.alterRetentionPolicy = function (name, options) {
586
- var q = "alter retention policy " + grammar.escape.quoted(name) + " on "
587
- + grammar.escape.quoted(options.database || this.defaultDB())
588
- + (" duration " + options.duration + " replication " + options.replication)
589
- + (options.isDefault ? ' default' : '');
590
- return this.pool.json(this.getQueryOpts({ q: q }, 'POST')).then(results_1.assertNoErrors);
591
- };
592
- /**
593
- * Deletes a retention policy and associated data. Note that the data will
594
- * not be immediately destroyed, and will hang around until Influx's
595
- * bi-hourly cron.
596
- *
597
- * @param {String} name The retention policy name
598
- * @param {String} [database] Database name that the policy lives in,
599
- * uses the default database if not provided.
600
- * @return {Promise<void>}
601
- * @example
602
- * influx.dropRetentionPolicy('7d')
603
- */
604
- InfluxDB.prototype.dropRetentionPolicy = function (name, database) {
605
- if (database === void 0) { database = this.defaultDB(); }
606
- return this.pool.json(this.getQueryOpts({
607
- q: "drop retention policy " + grammar.escape.quoted(name) + " "
608
- + ("on " + grammar.escape.quoted(database)),
609
- }, 'POST')).then(results_1.assertNoErrors);
610
- };
611
- /**
612
- * Shows retention policies on the database
613
- *
614
- * @param {String} [database] The database to list policies on, uses the
615
- * default database if not provided.
616
- * @return {Promise<Array<{
617
- * name: String,
618
- * duration: String,
619
- * shardGroupDuration: String,
620
- * replicaN: Number,
621
- * default: Boolean
622
- * }>>}
623
- * @example
624
- * influx.showRetentionPolicies().then(policies => {
625
- * expect(policies.slice()).to.deep.equal([
626
- * {
627
- * name: 'autogen',
628
- * duration: '0s',
629
- * shardGroupDuration: '168h0m0s',
630
- * replicaN: 1,
631
- * default: true,
632
- * },
633
- * {
634
- * name: '7d',
635
- * duration: '168h0m0s',
636
- * shardGroupDuration: '24h0m0s',
637
- * replicaN: 1,
638
- * default: false,
639
- * },
640
- * ])
641
- * })
642
- */
643
- InfluxDB.prototype.showRetentionPolicies = function (database) {
644
- if (database === void 0) { database = this.defaultDB(); }
645
- return this.pool.json(this.getQueryOpts({
646
- q: "show retention policies on " + grammar.escape.quoted(database),
647
- }, 'GET')).then(results_1.parseSingle);
648
- };
649
- /**
650
- * writePoints sends a list of points together in a batch to InfluxDB. In
651
- * each point you must specify the measurement name to write into as well
652
- * as a list of tag and field values. Optionally, you can specify the
653
- * time to tag that point at, defaulting to the current time.
654
- *
655
- * If you defined a schema for the measurement in the options you passed
656
- * to `new Influx(options)`, we'll use that to make sure that types get
657
- * cast correctly and that there are no extraneous fields or columns.
658
- *
659
- * For best performance, it's recommended that you batch your data into
660
- * sets of a couple thousand records before writing it. In the future we'll
661
- * have some utilities within node-influx to make this easier.
662
- *
663
- * ---
664
- *
665
- * A note when using manually-specified times and precisions: by default
666
- * we write using the `ms` precision since that's what JavaScript gives us.
667
- * You can adjust this. However, there is some special behaviour if you
668
- * manually specify a timestamp in your points:
669
- * - if you specify the timestamp as a Date object, we'll convert it to
670
- * milliseconds and manipulate it as needed to get the right precision
671
- * - if provide a INanoDate as returned from {@link toNanoTime} or the
672
- * results from an Influx query, we'll be able to pull the precise
673
- * nanosecond timestamp and manipulate it to get the right precision
674
- * - if you provide a string or number as the timestamp, we'll pass it
675
- * straight into Influx.
676
- *
677
- * Please see the IPoint and IWriteOptions types for a
678
- * full list of possible options.
679
- *
680
- * @param {IPoint[]} points
681
- * @param {IWriteOptions} [options]
682
- * @return {Promise<void>}
683
- * @example
684
- * // write a point into the default database with
685
- * // the default retention policy.
686
- * influx.writePoints([
687
- * {
688
- * measurement: 'perf',
689
- * tags: { host: 'box1.example.com' },
690
- * fields: { cpu: getCpuUsage(), mem: getMemUsage() },
691
- * }
692
- * ])
693
- *
694
- * // you can manually specify the database,
695
- * // retention policy, and time precision:
696
- * influx.writePoints([
697
- * {
698
- * measurement: 'perf',
699
- * tags: { host: 'box1.example.com' },
700
- * fields: { cpu: getCpuUsage(), mem: getMemUsage() },
701
- * timestamp: getLastRecordedTime(),
702
- * }
703
- * ], {
704
- * database: 'my_db',
705
- * retentionPolicy: '1d',
706
- * precision: 's'
707
- * })
708
- */
709
- InfluxDB.prototype.writePoints = function (points, options) {
710
- var _this = this;
711
- if (options === void 0) { options = {}; }
712
- var _a = options.database, database = _a === void 0 ? this.defaultDB() : _a, _b = options.precision, precision = _b === void 0 ? 'n' : _b, retentionPolicy = options.retentionPolicy;
713
- var payload = '';
714
- points.forEach(function (point) {
715
- var _a = point.fields, fields = _a === void 0 ? {} : _a, _b = point.tags, tags = _b === void 0 ? {} : _b, measurement = point.measurement, timestamp = point.timestamp;
716
- var schema = _this.schema[database] && _this.schema[database][measurement];
717
- var fieldsPairs = schema ? schema.coerceFields(fields) : schema_1.coerceBadly(fields);
718
- var tagsNames = schema ? schema.checkTags(tags) : Object.keys(tags);
719
- payload += (payload.length > 0 ? '\n' : '') + measurement;
720
- for (var i = 0; i < tagsNames.length; i += 1) {
721
- payload += ','
722
- + grammar.escape.tag(tagsNames[i])
723
- + '='
724
- + grammar.escape.tag(tags[tagsNames[i]]);
725
- }
726
- for (var i = 0; i < fieldsPairs.length; i += 1) {
727
- payload += (i === 0 ? ' ' : ',')
728
- + grammar.escape.tag(fieldsPairs[i][0])
729
- + '='
730
- + fieldsPairs[i][1];
731
- }
732
- if (timestamp !== undefined) {
733
- payload += ' ' + grammar.castTimestamp(timestamp, precision);
734
- }
735
- });
736
- return this.pool.discard({
737
- body: payload,
738
- method: 'POST',
739
- path: '/write',
740
- query: Object.assign({
741
- db: database,
742
- p: this.options.password,
743
- precision: precision,
744
- rp: retentionPolicy,
745
- u: this.options.username,
746
- }),
747
- });
748
- };
749
- /**
750
- * writeMeasurement functions similarly to {@link InfluxDB#writePoints}, but
751
- * it automatically fills in the `measurement` value for all points for you.
752
- *
753
- * @param {String} measurement
754
- * @param {IPoint[]} points
755
- * @param {IWriteOptions} [options]
756
- * @return {Promise<void>}
757
- * @example
758
- * influx.writeMeasurement('perf', [
759
- * {
760
- * tags: { host: 'box1.example.com' },
761
- * fields: { cpu: getCpuUsage(), mem: getMemUsage() },
762
- * }
763
- * ])
764
- */
765
- InfluxDB.prototype.writeMeasurement = function (measurement, points, options) {
766
- if (options === void 0) { options = {}; }
767
- points = points.map(function (p) { return Object.assign({ measurement: measurement }, p); });
768
- return this.writePoints(points, options);
769
- };
770
- /**
771
- * .query() runs a query (or list of queries), and returns the results in a
772
- * friendly format, {@link IResults}. If you run multiple queries, an array of results
773
- * will be returned, otherwise a single result (array of objects) will be returned.
774
- *
775
- * @param {String|String[]} query
776
- * @param {IQueryOptions} [options]
777
- * @return {Promise<IResults|Results[]>} result(s)
778
- * @example
779
- * influx.query('select * from perf').then(results => {
780
- * console.log(results)
781
- * })
782
- */
783
- InfluxDB.prototype.query = function (query, options) {
784
- if (options === void 0) { options = {}; }
785
- if (Array.isArray(query)) {
786
- query = query.join(';');
787
- }
788
- // If the consumer asked explicitly for nanosecond precision parsing,
789
- // remove that to cause Influx to give us ISO dates that
790
- // we can parse correctly.
791
- if (options.precision === 'n') {
792
- options = Object.assign({}, options); // avoid mutating
793
- delete options.precision;
794
- }
795
- return this.queryRaw(query, options).then(function (res) { return results_1.parse(res, options.precision); });
796
- };
797
- /**
798
- * queryRaw functions similarly to .query() but it does no fancy
799
- * transformations on the returned data; it calls `JSON.parse` and returns
800
- * those results verbatim.
801
- *
802
- * @param {String|String[]} query
803
- * @param {IQueryOptions} [options]
804
- * @return {Promise<*>}
805
- * @example
806
- * influx.queryRaw('select * from perf').then(rawData => {
807
- * console.log(rawData)
808
- * })
809
- */
810
- InfluxDB.prototype.queryRaw = function (query, options) {
811
- if (options === void 0) { options = {}; }
812
- var _a = options.database, database = _a === void 0 ? this.defaultDB() : _a, retentionPolicy = options.retentionPolicy;
813
- if (query instanceof Array) {
814
- query = query.join(';');
815
- }
816
- return this.pool.json(this.getQueryOpts({
817
- db: database,
818
- epoch: options.precision,
819
- q: query,
820
- rp: retentionPolicy,
821
- }));
822
- };
823
- /**
824
- * Pings all available hosts, collecting online status and version info.
825
- * @param {Number} timeout Given in milliseconds
826
- * @return {Promise<IPingStats[]>}
827
- * @example
828
- * influx.ping(5000).then(hosts => {
829
- * hosts.forEach(host => {
830
- * if (host.online) {
831
- * console.log(`${host.url.host} responded in ${host.rtt}ms running ${host.version})`)
832
- * } else {
833
- * console.log(`${host.url.host} is offline :(`)
834
- * }
835
- * })
836
- * })
837
- */
838
- InfluxDB.prototype.ping = function (timeout) {
839
- return this.pool.ping(timeout);
840
- };
841
- /**
842
- * Returns the default database that queries operates on. It throws if called
843
- * when a default database isn't set.
844
- * @private
845
- */
846
- InfluxDB.prototype.defaultDB = function () {
847
- if (!this.options.database) {
848
- throw new Error('Attempted to run an influx query without a default'
849
- + ' database specified or an explicit database provided.');
850
- }
851
- return this.options.database;
852
- };
853
- /**
854
- * Creates options to be passed into the pool to query databases.
855
- * @private
856
- */
857
- InfluxDB.prototype.getQueryOpts = function (params, method) {
858
- if (method === void 0) { method = 'GET'; }
859
- return {
860
- method: method,
861
- path: '/query',
862
- query: Object.assign({
863
- p: this.options.password,
864
- u: this.options.username,
865
- }, params),
866
- };
867
- };
868
- return InfluxDB;
869
- }());
870
- exports.InfluxDB = InfluxDB;
1
+ "use strict";
2
+ function __export(m) {
3
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
+ }
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ var url = require("url");
7
+ var b = require("./builder");
8
+ var grammar = require("./grammar");
9
+ var pool_1 = require("./pool");
10
+ var results_1 = require("./results");
11
+ var schema_1 = require("./schema");
12
+ var defaultHost = Object.freeze({
13
+ host: '127.0.0.1',
14
+ port: 8086,
15
+ protocol: 'http',
16
+ });
17
+ var defaultOptions = Object.freeze({
18
+ database: null,
19
+ hosts: [],
20
+ password: 'root',
21
+ schema: [],
22
+ username: 'root',
23
+ });
24
+ __export(require("./builder"));
25
+ var grammar_1 = require("./grammar");
26
+ exports.FieldType = grammar_1.FieldType;
27
+ exports.Precision = grammar_1.Precision;
28
+ exports.Raw = grammar_1.Raw;
29
+ exports.escape = grammar_1.escape;
30
+ exports.toNanoDate = grammar_1.toNanoDate;
31
+ var results_2 = require("./results");
32
+ exports.ResultError = results_2.ResultError;
33
+ /**
34
+ * Parses the URL out into into a IClusterConfig object
35
+ */
36
+ function parseOptionsUrl(addr) {
37
+ var parsed = url.parse(addr);
38
+ var options = {
39
+ host: parsed.hostname,
40
+ port: Number(parsed.port),
41
+ protocol: parsed.protocol.slice(0, -1),
42
+ };
43
+ if (parsed.auth) {
44
+ _a = parsed.auth.split(':'), options.username = _a[0], options.password = _a[1];
45
+ }
46
+ if (parsed.pathname.length > 1) {
47
+ options.database = parsed.pathname.slice(1);
48
+ }
49
+ return options;
50
+ var _a;
51
+ }
52
+ /**
53
+ * Works similarly to Object.assign, but only overwrites
54
+ * properties that resolve to undefined.
55
+ */
56
+ function defaults(target) {
57
+ var srcs = [];
58
+ for (var _i = 1; _i < arguments.length; _i++) {
59
+ srcs[_i - 1] = arguments[_i];
60
+ }
61
+ srcs.forEach(function (src) {
62
+ Object.keys(src).forEach(function (key) {
63
+ if (target[key] === undefined) {
64
+ target[key] = src[key];
65
+ }
66
+ });
67
+ });
68
+ return target;
69
+ }
70
+ /**
71
+ * InfluxDB is the public interface to run queries against the your database.
72
+ * This is a 'driver-level' module, not a a full-fleged ORM or ODM; you run
73
+ * queries directly by calling methods on this class.
74
+ *
75
+ * Please check out some of [the tutorials](https://node-influx.github.io/manual/tutorial.html)
76
+ * if you want help getting started!
77
+ *
78
+ * @example
79
+ * const Influx = require('influx');
80
+ * const influx = new Influx.InfluxDB({
81
+ * host: 'localhost',
82
+ * database: 'express_response_db',
83
+ * schema: [
84
+ * {
85
+ * measurement: 'response_times',
86
+ * fields: {
87
+ * path: Influx.FieldType.STRING,
88
+ * duration: Influx.FieldType.INTEGER
89
+ * },
90
+ * tags: [
91
+ * 'host'
92
+ * ]
93
+ * }
94
+ * ]
95
+ * })
96
+ *
97
+ * influx.writePoints([
98
+ * {
99
+ * measurement: 'response_times',
100
+ * tags: { host: os.hostname() },
101
+ * fields: { duration, path: req.path },
102
+ * }
103
+ * ]).then(() => {
104
+ * return influx.query(`
105
+ * select * from response_times
106
+ * where host = ${Influx.escape.stringLit(os.hostname())}
107
+ * order by time desc
108
+ * limit 10
109
+ * `)
110
+ * }).then(rows => {
111
+ * rows.forEach(row => console.log(`A request to ${row.path} took ${row.duration}ms`))
112
+ * })
113
+ */
114
+ var InfluxDB = (function () {
115
+ /**
116
+ * Connect to a single InfluxDB instance by specifying
117
+ * a set of connection options.
118
+ * @param {IClusterConfig|ISingleHostConfig|string} [options='http://root:root@127.0.0.1:8086']
119
+ *
120
+ * @example
121
+ * const Influx = require('influx')
122
+ *
123
+ * // Connect to a single host with a DSN:
124
+ * const influx = new Influx.InfluxDB('http://user:password@host:8086/database')
125
+ *
126
+ * @example
127
+ * const Influx = require('influx')
128
+ *
129
+ * // Connect to a single host with a full set of config details and
130
+ * // a custom schema
131
+ * const client = new Influx.InfluxDB({
132
+ * database: 'my_db',
133
+ * host: 'localhost',
134
+ * port: 8086,
135
+ * username: 'connor',
136
+ * password: 'pa$$w0rd',
137
+ * schema: [
138
+ * {
139
+ * measurement: 'perf',
140
+ * fields: {
141
+ * memory_usage: Influx.FieldType.INTEGER,
142
+ * cpu_usage: Influx.FieldType.FLOAT,
143
+ * is_online: Influx.FieldType.BOOLEAN
144
+ * }
145
+ * tags: [
146
+ * 'hostname'
147
+ * ]
148
+ * }
149
+ * ]
150
+ * })
151
+ *
152
+ * @example
153
+ * const Influx = require('influx')
154
+ *
155
+ * // Use a pool of several host connections and balance queries across them:
156
+ * const client = new Influx.InfluxDB({
157
+ * database: 'my_db',
158
+ * username: 'connor',
159
+ * password: 'pa$$w0rd',
160
+ * hosts: [
161
+ * { host: 'db1.example.com' },
162
+ * { host: 'db2.example.com' },
163
+ * ],
164
+ * schema: [
165
+ * {
166
+ * measurement: 'perf',
167
+ * fields: {
168
+ * memory_usage: Influx.FieldType.INTEGER,
169
+ * cpu_usage: Influx.FieldType.FLOAT,
170
+ * is_online: Influx.FieldType.BOOLEAN
171
+ * }
172
+ * tags: [
173
+ * 'hostname'
174
+ * ]
175
+ * }
176
+ * ]
177
+ * })
178
+ *
179
+ */
180
+ function InfluxDB(options) {
181
+ var _this = this;
182
+ /**
183
+ * Map of Schema instances defining measurements in Influx.
184
+ * @private
185
+ */
186
+ this.schema = Object.create(null);
187
+ // Figure out how to parse whatever we were passed in into a IClusterConfig.
188
+ if (typeof options === 'string') {
189
+ options = parseOptionsUrl(options);
190
+ }
191
+ else if (!options) {
192
+ options = defaultHost;
193
+ }
194
+ if (!options.hasOwnProperty('hosts')) {
195
+ options = {
196
+ database: options.database,
197
+ hosts: [options],
198
+ password: options.password,
199
+ pool: options.pool,
200
+ schema: options.schema,
201
+ username: options.username,
202
+ };
203
+ }
204
+ var resolved = options;
205
+ resolved.hosts = resolved.hosts.map(function (host) {
206
+ return defaults({
207
+ host: host.host,
208
+ port: host.port,
209
+ protocol: host.protocol,
210
+ options: host.options,
211
+ }, defaultHost);
212
+ });
213
+ this.pool = new pool_1.Pool(resolved.pool);
214
+ this.options = defaults(resolved, defaultOptions);
215
+ resolved.hosts.forEach(function (host) {
216
+ _this.pool.addHost(host.protocol + "://" + host.host + ":" + host.port, host.options);
217
+ });
218
+ this.options.schema.forEach(function (schema) {
219
+ var db = schema.database = schema.database || _this.options.database;
220
+ if (!db) {
221
+ throw new Error("Schema " + schema.measurement + " doesn't have a database specified," +
222
+ 'and no default database is provided!');
223
+ }
224
+ if (!_this.schema[db]) {
225
+ _this.schema[db] = Object.create(null);
226
+ }
227
+ _this.schema[db][schema.measurement] = new schema_1.Schema(schema);
228
+ });
229
+ }
230
+ /**
231
+ * Creates a new database with the provided name.
232
+ * @param {string} databaseName
233
+ * @return {Promise.<void>}
234
+ * @example
235
+ * influx.createDatabase('mydb')
236
+ */
237
+ InfluxDB.prototype.createDatabase = function (databaseName) {
238
+ return this.pool.json(this.getQueryOpts({
239
+ q: "create database " + grammar.escape.quoted(databaseName),
240
+ }, 'POST')).then(results_1.assertNoErrors);
241
+ };
242
+ /**
243
+ * Deletes a database with the provided name.
244
+ * @param {string} databaseName
245
+ * @return {Promise.<void>}
246
+ * @example
247
+ * influx.createDatabase('mydb')
248
+ */
249
+ InfluxDB.prototype.dropDatabase = function (databaseName) {
250
+ return this.pool.json(this.getQueryOpts({
251
+ q: "drop database " + grammar.escape.quoted(databaseName),
252
+ }, 'POST')).then(results_1.assertNoErrors);
253
+ };
254
+ /**
255
+ * Returns array of database names. Requires cluster admin privileges.
256
+ * @returns {Promise<String[]>} a list of database names
257
+ * @example
258
+ * influx.getMeasurements().then(names =>
259
+ * console.log('My database names are: ' + names.join(', ')));
260
+ */
261
+ InfluxDB.prototype.getDatabaseNames = function () {
262
+ return this.pool.json(this.getQueryOpts({ q: 'show databases' }))
263
+ .then(function (res) { return results_1.parseSingle(res).map(function (r) { return r.name; }); });
264
+ };
265
+ /**
266
+ * Returns array of measurements.
267
+ * @returns {Promise<String[]>} a list of measurement names
268
+ * @param {String} [database] the database the measurement lives in, optional
269
+ * if a default database is provided.
270
+ * @example
271
+ * influx.getMeasurements().then(names =>
272
+ * console.log('My measurement names are: ' + names.join(', ')));
273
+ */
274
+ InfluxDB.prototype.getMeasurements = function (database) {
275
+ if (database === void 0) { database = this.defaultDB(); }
276
+ return this.pool.json(this.getQueryOpts({
277
+ db: database,
278
+ q: 'show measurements',
279
+ })).then(function (res) { return results_1.parseSingle(res).map(function (r) { return r.name; }); });
280
+ };
281
+ /**
282
+ * Returns a list of all series within the target measurement, or from the
283
+ * entire database if a measurement isn't provided.
284
+ * @param {Object} [options]
285
+ * @param {String} [options.measurement] if provided, we'll only get series
286
+ * from within that measurement.
287
+ * @param {String} [options.database] the database the series lives in,
288
+ * optional if a default database is provided.
289
+ * @returns {Promise<String[]>} a list of series names
290
+ * @example
291
+ * influx.getSeries().then(names => {
292
+ * console.log('My series names in my_measurement are: ' + names.join(', '))
293
+ * })
294
+ *
295
+ * influx.getSeries({
296
+ * measurement: 'my_measurement',
297
+ * database: 'my_db'
298
+ * }).then(names => {
299
+ * console.log('My series names in my_measurement are: ' + names.join(', '))
300
+ * })
301
+ */
302
+ InfluxDB.prototype.getSeries = function (options) {
303
+ if (options === void 0) { options = {}; }
304
+ var _a = options.database, database = _a === void 0 ? this.defaultDB() : _a, measurement = options.measurement;
305
+ var query = 'show series';
306
+ if (measurement) {
307
+ query += " from " + grammar.escape.quoted(measurement);
308
+ }
309
+ return this.pool.json(this.getQueryOpts({
310
+ db: database,
311
+ q: query,
312
+ })).then(function (res) { return results_1.parseSingle(res).map(function (r) { return r.key; }); });
313
+ };
314
+ /**
315
+ * Removes a measurement from the database.
316
+ * @param {String} measurement
317
+ * @param {String} [database] the database the measurement lives in, optional
318
+ * if a default database is provided.
319
+ * @return {Promise.<void>}
320
+ * @example
321
+ * influx.dropMeasurement('my_measurement')
322
+ */
323
+ InfluxDB.prototype.dropMeasurement = function (measurement, database) {
324
+ if (database === void 0) { database = this.defaultDB(); }
325
+ return this.pool.json(this.getQueryOpts({
326
+ db: database,
327
+ q: "drop measurement " + grammar.escape.quoted(measurement),
328
+ }, 'POST')).then(results_1.assertNoErrors);
329
+ };
330
+ /**
331
+ * Removes a one or more series from InfluxDB.
332
+ *
333
+ * @returns {Promise<void>}
334
+ * @example
335
+ * // The following pairs of queries are equivalent: you can chose either to
336
+ * // use our builder or pass in string directly. The builder takes care
337
+ * // of escaping and most syntax handling for you.
338
+ *
339
+ * influx.dropSeries({ where: e => e.tag('cpu').equals.value('cpu8') })
340
+ * influx.dropSeries({ where: '"cpu" = \'cpu8\'' })
341
+ * // DROP SERIES WHERE "cpu" = 'cpu8'
342
+ *
343
+ * influx.dropSeries({ measurement: m => m.name('cpu').policy('autogen') })
344
+ * influx.dropSeries({ measurement: '"cpu"."autogen"' })
345
+ * // DROP SERIES FROM "autogen"."cpu"
346
+ *
347
+ * influx.dropSeries({
348
+ * measurement: m => m.name('cpu').policy('autogen'),
349
+ * where: e => e.tag('cpu').equals.value('cpu8'),
350
+ * database: 'my_db'
351
+ * })
352
+ * // DROP SERIES FROM "autogen"."cpu" WHERE "cpu" = 'cpu8'
353
+ */
354
+ InfluxDB.prototype.dropSeries = function (options) {
355
+ var db = 'database' in options ? options.database : this.defaultDB();
356
+ var q = 'drop series';
357
+ if ('measurement' in options) {
358
+ q += ' from ' + b.parseMeasurement(options);
359
+ }
360
+ if ('where' in options) {
361
+ q += ' where ' + b.parseWhere(options);
362
+ }
363
+ return this.pool.json(this.getQueryOpts({ db: db, q: q }, 'POST')).then(results_1.assertNoErrors);
364
+ };
365
+ /**
366
+ * Returns a list of users on the Influx database.
367
+ * @return {Promise<Array<{ user: String, admin: Boolean }>>}
368
+ * @example
369
+ * influx.getUsers().then(users => {
370
+ * users.forEach(user => {
371
+ * if (user.admin) {
372
+ * console.log(user.user, 'is an admin!')
373
+ * } else {
374
+ * console.log(user.user, 'is not an admin!')
375
+ * }
376
+ * })
377
+ * })
378
+ */
379
+ InfluxDB.prototype.getUsers = function () {
380
+ return this.pool.json(this.getQueryOpts({ q: 'show users' })).then(results_1.parseSingle);
381
+ };
382
+ /**
383
+ * Creates a new InfluxDB user.
384
+ * @param {String} username
385
+ * @param {String} password
386
+ * @param {Boolean} [admin=false] If true, the user will be given all
387
+ * privileges on all databases.
388
+ * @return {Promise<void>}
389
+ * @example
390
+ * influx.createUser('connor', 'pa55w0rd', true) // make 'connor' an admin
391
+ *
392
+ * // make non-admins:
393
+ * influx.createUser('not_admin', 'pa55w0rd')
394
+ */
395
+ InfluxDB.prototype.createUser = function (username, password, admin) {
396
+ if (admin === void 0) { admin = false; }
397
+ return this.pool.json(this.getQueryOpts({
398
+ q: "create user " + grammar.escape.quoted(username) + " with password "
399
+ + grammar.escape.stringLit(password)
400
+ + (admin ? ' with all privileges' : ''),
401
+ }, 'POST')).then(results_1.assertNoErrors);
402
+ };
403
+ /**
404
+ * Sets a password for an Influx user.
405
+ * @param {String} username
406
+ * @param {String} password
407
+ * @return {Promise<void>}
408
+ * @example
409
+ * influx.setPassword('connor', 'pa55w0rd')
410
+ */
411
+ InfluxDB.prototype.setPassword = function (username, password) {
412
+ return this.pool.json(this.getQueryOpts({
413
+ q: "set password for " + grammar.escape.quoted(username) + " = "
414
+ + grammar.escape.stringLit(password),
415
+ }, 'POST')).then(results_1.assertNoErrors);
416
+ };
417
+ /**
418
+ * Grants a privilege to a specified user.
419
+ * @param {String} username
420
+ * @param {String} privilege Should be one of 'READ' or 'WRITE'
421
+ * @param {String} [database] If not provided, uses the default database.
422
+ * @return {Promise<void>}
423
+ * @example
424
+ * influx.grantPrivilege('connor', 'READ', 'my_db') // grants read access on my_db to connor
425
+ */
426
+ InfluxDB.prototype.grantPrivilege = function (username, privilege, database) {
427
+ if (database === void 0) { database = this.defaultDB(); }
428
+ return this.pool.json(this.getQueryOpts({
429
+ q: "grant " + privilege + " on " + grammar.escape.quoted(database) + " "
430
+ + ("to " + grammar.escape.quoted(username)),
431
+ }, 'POST')).then(results_1.assertNoErrors);
432
+ };
433
+ /**
434
+ * Removes a privilege from a specified user.
435
+ * @param {String} username
436
+ * @param {String} privilege Should be one of 'READ' or 'WRITE'
437
+ * @param {String} [database] If not provided, uses the default database.
438
+ * @return {Promise<void>}
439
+ * @example
440
+ * influx.revokePrivilege('connor', 'READ', 'my_db') // removes read access on my_db from connor
441
+ */
442
+ InfluxDB.prototype.revokePrivilege = function (username, privilege, database) {
443
+ if (database === void 0) { database = this.defaultDB(); }
444
+ return this.pool.json(this.getQueryOpts({
445
+ q: "revoke " + privilege + " on " + grammar.escape.quoted(database) + " from "
446
+ + grammar.escape.quoted(username),
447
+ }, 'POST')).then(results_1.assertNoErrors);
448
+ };
449
+ /**
450
+ * Grants admin privileges to a specified user.
451
+ * @param {String} username
452
+ * @return {Promise<void>}
453
+ * @example
454
+ * influx.grantAdminPrivilege('connor')
455
+ */
456
+ InfluxDB.prototype.grantAdminPrivilege = function (username) {
457
+ return this.pool.json(this.getQueryOpts({
458
+ q: "grant all to " + grammar.escape.quoted(username),
459
+ }, 'POST')).then(results_1.assertNoErrors);
460
+ };
461
+ /**
462
+ * Removes a admin privilege from a specified user.
463
+ * @param {String} username
464
+ * @return {Promise<void>}
465
+ * @example
466
+ * influx.revokeAdminPrivilege('connor')
467
+ */
468
+ InfluxDB.prototype.revokeAdminPrivilege = function (username) {
469
+ return this.pool.json(this.getQueryOpts({
470
+ q: "revoke all from " + grammar.escape.quoted(username),
471
+ }, 'POST')).then(results_1.assertNoErrors);
472
+ };
473
+ /**
474
+ * Removes a user from the database.
475
+ * @param {String} username
476
+ * @return {Promise<void>}
477
+ * @example
478
+ * influx.dropUser('connor')
479
+ */
480
+ InfluxDB.prototype.dropUser = function (username) {
481
+ return this.pool.json(this.getQueryOpts({
482
+ q: "drop user " + grammar.escape.quoted(username),
483
+ }, 'POST')).then(results_1.assertNoErrors);
484
+ };
485
+ /**
486
+ * Creates a continuous query in a database
487
+ * @param {String} name The query name, for later reference
488
+ * @param {String} query The body of the query to run
489
+ * @param {String} [database] If not provided, uses the default database.
490
+ * @return {Promise<void>}
491
+ * @example
492
+ * influx.createContinuousQuery('downsample_cpu_1h', `
493
+ * SELECT MEAN(cpu) INTO "7d"."perf"
494
+ * FROM "1d"."perf" GROUP BY time(1m)
495
+ * `)
496
+ */
497
+ InfluxDB.prototype.createContinuousQuery = function (name, query, database) {
498
+ if (database === void 0) { database = this.defaultDB(); }
499
+ return this.pool.json(this.getQueryOpts({
500
+ q: "create continuous query " + grammar.escape.quoted(name)
501
+ + (" on " + grammar.escape.quoted(database) + " begin " + query + " end"),
502
+ }, 'POST')).then(results_1.assertNoErrors);
503
+ };
504
+ /**
505
+ * Returns a list of continous queries in the database.
506
+ * @param {String} [database] If not provided, uses the default database.
507
+ * @return {Promise<void>}
508
+ * @example
509
+ * influx.showContinousQueries()
510
+ */
511
+ InfluxDB.prototype.showContinousQueries = function (database) {
512
+ if (database === void 0) { database = this.defaultDB(); }
513
+ return this.pool.json(this.getQueryOpts({
514
+ db: database,
515
+ q: 'show continuous queries',
516
+ })).then(results_1.parseSingle);
517
+ };
518
+ /**
519
+ * Creates a continuous query in a database
520
+ * @param {String} name The query name
521
+ * @param {String} [database] If not provided, uses the default database.
522
+ * @return {Promise<void>}
523
+ * @example
524
+ * influx.dropContinuousQuery('downsample_cpu_1h')
525
+ */
526
+ InfluxDB.prototype.dropContinuousQuery = function (name, database) {
527
+ if (database === void 0) { database = this.defaultDB(); }
528
+ return this.pool.json(this.getQueryOpts({
529
+ q: "drop continuous query " + grammar.escape.quoted(name)
530
+ + (" on " + grammar.escape.quoted(database)),
531
+ }, 'POST')).then(results_1.assertNoErrors);
532
+ };
533
+ /**
534
+ * Creates a new retention policy on a database. You can read more about
535
+ * [Downsampling and Retention](https://docs.influxdata.com/influxdb/v1.0/
536
+ * guides/downsampling_and_retention/) on the InfluxDB website.
537
+ *
538
+ * @param {String} name The retention policy name
539
+ * @param {Object} options
540
+ * @param {String} [options.database] Database to create the policy on,
541
+ * uses the default database if not provided.
542
+ * @param {String} options.duration How long data in the retention policy
543
+ * should be stored for, should be in a format like `7d`. See details
544
+ * [here](https://docs.influxdata.com/influxdb/v1.0/query_language/spec/#durations)
545
+ * @param {Number} options.replication How many servers data in the series
546
+ * should be replicated to.
547
+ * @param {Boolean} [options.isDefault] Whether the retention policy should
548
+ * be the default policy on the database.
549
+ * @return {Promise<void>}
550
+ * @example
551
+ * influx.createRetentionPolicy('7d', {
552
+ * duration: '7d',
553
+ * replication: 1
554
+ * })
555
+ */
556
+ InfluxDB.prototype.createRetentionPolicy = function (name, options) {
557
+ var q = "create retention policy " + grammar.escape.quoted(name) + " on "
558
+ + grammar.escape.quoted(options.database || this.defaultDB())
559
+ + (" duration " + options.duration + " replication " + options.replication)
560
+ + (options.isDefault ? ' default' : '');
561
+ return this.pool.json(this.getQueryOpts({ q: q }, 'POST')).then(results_1.assertNoErrors);
562
+ };
563
+ /**
564
+ * Alters an existing retention policy on a database.
565
+ *
566
+ * @param {String} name The retention policy name
567
+ * @param {Object} options
568
+ * @param {String} [options.database] Database to create the policy on,
569
+ * uses the default database if not provided.
570
+ * @param {String} options.duration How long data in the retention policy
571
+ * should be stored for, should be in a format like `7d`. See details
572
+ * [here](https://docs.influxdata.com/influxdb/v1.0/query_language/spec/#durations)
573
+ * @param {Number} options.replication How many servers data in the series
574
+ * should be replicated to.
575
+ * @param {Boolean} [options.default] Whether the retention policy should
576
+ * be the default policy on the database.
577
+ * @return {Promise<void>}
578
+ * @example
579
+ * influx.alterRetentionPolicy('7d', {
580
+ * duration: '7d',
581
+ * replication: 1,
582
+ * default: true
583
+ * })
584
+ */
585
+ InfluxDB.prototype.alterRetentionPolicy = function (name, options) {
586
+ var q = "alter retention policy " + grammar.escape.quoted(name) + " on "
587
+ + grammar.escape.quoted(options.database || this.defaultDB())
588
+ + (" duration " + options.duration + " replication " + options.replication)
589
+ + (options.isDefault ? ' default' : '');
590
+ return this.pool.json(this.getQueryOpts({ q: q }, 'POST')).then(results_1.assertNoErrors);
591
+ };
592
+ /**
593
+ * Deletes a retention policy and associated data. Note that the data will
594
+ * not be immediately destroyed, and will hang around until Influx's
595
+ * bi-hourly cron.
596
+ *
597
+ * @param {String} name The retention policy name
598
+ * @param {String} [database] Database name that the policy lives in,
599
+ * uses the default database if not provided.
600
+ * @return {Promise<void>}
601
+ * @example
602
+ * influx.dropRetentionPolicy('7d')
603
+ */
604
+ InfluxDB.prototype.dropRetentionPolicy = function (name, database) {
605
+ if (database === void 0) { database = this.defaultDB(); }
606
+ return this.pool.json(this.getQueryOpts({
607
+ q: "drop retention policy " + grammar.escape.quoted(name) + " "
608
+ + ("on " + grammar.escape.quoted(database)),
609
+ }, 'POST')).then(results_1.assertNoErrors);
610
+ };
611
+ /**
612
+ * Shows retention policies on the database
613
+ *
614
+ * @param {String} [database] The database to list policies on, uses the
615
+ * default database if not provided.
616
+ * @return {Promise<Array<{
617
+ * name: String,
618
+ * duration: String,
619
+ * shardGroupDuration: String,
620
+ * replicaN: Number,
621
+ * default: Boolean
622
+ * }>>}
623
+ * @example
624
+ * influx.showRetentionPolicies().then(policies => {
625
+ * expect(policies.slice()).to.deep.equal([
626
+ * {
627
+ * name: 'autogen',
628
+ * duration: '0s',
629
+ * shardGroupDuration: '168h0m0s',
630
+ * replicaN: 1,
631
+ * default: true,
632
+ * },
633
+ * {
634
+ * name: '7d',
635
+ * duration: '168h0m0s',
636
+ * shardGroupDuration: '24h0m0s',
637
+ * replicaN: 1,
638
+ * default: false,
639
+ * },
640
+ * ])
641
+ * })
642
+ */
643
+ InfluxDB.prototype.showRetentionPolicies = function (database) {
644
+ if (database === void 0) { database = this.defaultDB(); }
645
+ return this.pool.json(this.getQueryOpts({
646
+ q: "show retention policies on " + grammar.escape.quoted(database),
647
+ }, 'GET')).then(results_1.parseSingle);
648
+ };
649
+ /**
650
+ * writePoints sends a list of points together in a batch to InfluxDB. In
651
+ * each point you must specify the measurement name to write into as well
652
+ * as a list of tag and field values. Optionally, you can specify the
653
+ * time to tag that point at, defaulting to the current time.
654
+ *
655
+ * If you defined a schema for the measurement in the options you passed
656
+ * to `new Influx(options)`, we'll use that to make sure that types get
657
+ * cast correctly and that there are no extraneous fields or columns.
658
+ *
659
+ * For best performance, it's recommended that you batch your data into
660
+ * sets of a couple thousand records before writing it. In the future we'll
661
+ * have some utilities within node-influx to make this easier.
662
+ *
663
+ * ---
664
+ *
665
+ * A note when using manually-specified times and precisions: by default
666
+ * we write using the `ms` precision since that's what JavaScript gives us.
667
+ * You can adjust this. However, there is some special behaviour if you
668
+ * manually specify a timestamp in your points:
669
+ * - if you specify the timestamp as a Date object, we'll convert it to
670
+ * milliseconds and manipulate it as needed to get the right precision
671
+ * - if provide a INanoDate as returned from {@link toNanoTime} or the
672
+ * results from an Influx query, we'll be able to pull the precise
673
+ * nanosecond timestamp and manipulate it to get the right precision
674
+ * - if you provide a string or number as the timestamp, we'll pass it
675
+ * straight into Influx.
676
+ *
677
+ * Please see the IPoint and IWriteOptions types for a
678
+ * full list of possible options.
679
+ *
680
+ * @param {IPoint[]} points
681
+ * @param {IWriteOptions} [options]
682
+ * @return {Promise<void>}
683
+ * @example
684
+ * // write a point into the default database with
685
+ * // the default retention policy.
686
+ * influx.writePoints([
687
+ * {
688
+ * measurement: 'perf',
689
+ * tags: { host: 'box1.example.com' },
690
+ * fields: { cpu: getCpuUsage(), mem: getMemUsage() },
691
+ * }
692
+ * ])
693
+ *
694
+ * // you can manually specify the database,
695
+ * // retention policy, and time precision:
696
+ * influx.writePoints([
697
+ * {
698
+ * measurement: 'perf',
699
+ * tags: { host: 'box1.example.com' },
700
+ * fields: { cpu: getCpuUsage(), mem: getMemUsage() },
701
+ * timestamp: getLastRecordedTime(),
702
+ * }
703
+ * ], {
704
+ * database: 'my_db',
705
+ * retentionPolicy: '1d',
706
+ * precision: 's'
707
+ * })
708
+ */
709
+ InfluxDB.prototype.writePoints = function (points, options) {
710
+ var _this = this;
711
+ if (options === void 0) { options = {}; }
712
+ var _a = options.database, database = _a === void 0 ? this.defaultDB() : _a, _b = options.precision, precision = _b === void 0 ? 'n' : _b, retentionPolicy = options.retentionPolicy;
713
+ var payload = '';
714
+ points.forEach(function (point) {
715
+ var _a = point.fields, fields = _a === void 0 ? {} : _a, _b = point.tags, tags = _b === void 0 ? {} : _b, measurement = point.measurement, timestamp = point.timestamp;
716
+ var schema = _this.schema[database] && _this.schema[database][measurement];
717
+ var fieldsPairs = schema ? schema.coerceFields(fields) : schema_1.coerceBadly(fields);
718
+ var tagsNames = schema ? schema.checkTags(tags) : Object.keys(tags);
719
+ payload += (payload.length > 0 ? '\n' : '') + measurement;
720
+ for (var i = 0; i < tagsNames.length; i += 1) {
721
+ payload += ','
722
+ + grammar.escape.tag(tagsNames[i])
723
+ + '='
724
+ + grammar.escape.tag(tags[tagsNames[i]]);
725
+ }
726
+ for (var i = 0; i < fieldsPairs.length; i += 1) {
727
+ payload += (i === 0 ? ' ' : ',')
728
+ + grammar.escape.tag(fieldsPairs[i][0])
729
+ + '='
730
+ + fieldsPairs[i][1];
731
+ }
732
+ if (timestamp !== undefined) {
733
+ payload += ' ' + grammar.castTimestamp(timestamp, precision);
734
+ }
735
+ });
736
+ return this.pool.discard({
737
+ body: payload,
738
+ method: 'POST',
739
+ path: '/write',
740
+ query: Object.assign({
741
+ db: database,
742
+ p: this.options.password,
743
+ precision: precision,
744
+ rp: retentionPolicy,
745
+ u: this.options.username,
746
+ }),
747
+ });
748
+ };
749
+ /**
750
+ * writeMeasurement functions similarly to {@link InfluxDB#writePoints}, but
751
+ * it automatically fills in the `measurement` value for all points for you.
752
+ *
753
+ * @param {String} measurement
754
+ * @param {IPoint[]} points
755
+ * @param {IWriteOptions} [options]
756
+ * @return {Promise<void>}
757
+ * @example
758
+ * influx.writeMeasurement('perf', [
759
+ * {
760
+ * tags: { host: 'box1.example.com' },
761
+ * fields: { cpu: getCpuUsage(), mem: getMemUsage() },
762
+ * }
763
+ * ])
764
+ */
765
+ InfluxDB.prototype.writeMeasurement = function (measurement, points, options) {
766
+ if (options === void 0) { options = {}; }
767
+ points = points.map(function (p) { return Object.assign({ measurement: measurement }, p); });
768
+ return this.writePoints(points, options);
769
+ };
770
+ /**
771
+ * .query() runs a query (or list of queries), and returns the results in a
772
+ * friendly format, {@link IResults}. If you run multiple queries, an array of results
773
+ * will be returned, otherwise a single result (array of objects) will be returned.
774
+ *
775
+ * @param {String|String[]} query
776
+ * @param {IQueryOptions} [options]
777
+ * @return {Promise<IResults|Results[]>} result(s)
778
+ * @example
779
+ * influx.query('select * from perf').then(results => {
780
+ * console.log(results)
781
+ * })
782
+ */
783
+ InfluxDB.prototype.query = function (query, options) {
784
+ if (options === void 0) { options = {}; }
785
+ if (Array.isArray(query)) {
786
+ query = query.join(';');
787
+ }
788
+ // If the consumer asked explicitly for nanosecond precision parsing,
789
+ // remove that to cause Influx to give us ISO dates that
790
+ // we can parse correctly.
791
+ if (options.precision === 'n') {
792
+ options = Object.assign({}, options); // avoid mutating
793
+ delete options.precision;
794
+ }
795
+ return this.queryRaw(query, options).then(function (res) { return results_1.parse(res, options.precision); });
796
+ };
797
+ /**
798
+ * queryRaw functions similarly to .query() but it does no fancy
799
+ * transformations on the returned data; it calls `JSON.parse` and returns
800
+ * those results verbatim.
801
+ *
802
+ * @param {String|String[]} query
803
+ * @param {IQueryOptions} [options]
804
+ * @return {Promise<*>}
805
+ * @example
806
+ * influx.queryRaw('select * from perf').then(rawData => {
807
+ * console.log(rawData)
808
+ * })
809
+ */
810
+ InfluxDB.prototype.queryRaw = function (query, options) {
811
+ if (options === void 0) { options = {}; }
812
+ var _a = options.database, database = _a === void 0 ? this.defaultDB() : _a, retentionPolicy = options.retentionPolicy;
813
+ if (query instanceof Array) {
814
+ query = query.join(';');
815
+ }
816
+ return this.pool.json(this.getQueryOpts({
817
+ db: database,
818
+ epoch: options.precision,
819
+ q: query,
820
+ rp: retentionPolicy,
821
+ }));
822
+ };
823
+ /**
824
+ * Pings all available hosts, collecting online status and version info.
825
+ * @param {Number} timeout Given in milliseconds
826
+ * @return {Promise<IPingStats[]>}
827
+ * @example
828
+ * influx.ping(5000).then(hosts => {
829
+ * hosts.forEach(host => {
830
+ * if (host.online) {
831
+ * console.log(`${host.url.host} responded in ${host.rtt}ms running ${host.version})`)
832
+ * } else {
833
+ * console.log(`${host.url.host} is offline :(`)
834
+ * }
835
+ * })
836
+ * })
837
+ */
838
+ InfluxDB.prototype.ping = function (timeout) {
839
+ return this.pool.ping(timeout);
840
+ };
841
+ /**
842
+ * Returns the default database that queries operates on. It throws if called
843
+ * when a default database isn't set.
844
+ * @private
845
+ */
846
+ InfluxDB.prototype.defaultDB = function () {
847
+ if (!this.options.database) {
848
+ throw new Error('Attempted to run an influx query without a default'
849
+ + ' database specified or an explicit database provided.');
850
+ }
851
+ return this.options.database;
852
+ };
853
+ /**
854
+ * Creates options to be passed into the pool to query databases.
855
+ * @private
856
+ */
857
+ InfluxDB.prototype.getQueryOpts = function (params, method) {
858
+ if (method === void 0) { method = 'GET'; }
859
+ return {
860
+ method: method,
861
+ path: '/query',
862
+ query: Object.assign({
863
+ p: this.options.password,
864
+ u: this.options.username,
865
+ }, params),
866
+ };
867
+ };
868
+ return InfluxDB;
869
+ }());
870
+ exports.InfluxDB = InfluxDB;