/// import { RequestOptions } from "https"; import * as b from "./builder"; import * as grammar from "./grammar"; import { IPingStats, IPoolOptions } from "./pool"; import { IResults } from "./results"; import { ISchemaOptions } from "./schema"; export * from "./builder"; export { INanoDate, FieldType, Precision, Raw, TimePrecision, escape, toNanoDate, } from "./grammar"; export { ISchemaOptions } from "./schema"; export { IPingStats, IPoolOptions } from "./pool"; export { IResults, IResponse, ResultError } from "./results"; export interface IHostConfig { /** * Influx host to connect to, defaults to 127.0.0.1. */ host?: string; /** * Influx port to connect to, defaults to 8086. */ port?: number; /** * Path for Influx within the host, defaults to ''. * May be used if Influx is behind a reverse proxy or load balancer. */ path?: string; /** * Protocol to connect over, defaults to 'http'. */ protocol?: "http" | "https"; /** * Optional request option overrides. */ options?: RequestOptions; } export interface ISingleHostConfig extends IHostConfig { /** * Username for connecting to the database. Defaults to 'root'. */ username?: string; /** * Password for connecting to the database. Defaults to 'root'. */ password?: string; /** * Default database to write information to. */ database?: string; /** * Settings for the connection pool. */ pool?: IPoolOptions; /** * A list of schema for measurements in the database. */ schema?: ISchemaOptions[]; } export interface IClusterConfig { /** * Username for connecting to the database. Defaults to 'root'. */ username?: string; /** * Password for connecting to the database. Defaults to 'root'. */ password?: string; /** * Default database to write information to. */ database?: string; /** * A list of cluster hosts to connect to. */ hosts: IHostConfig[]; /** * Settings for the connection pool. */ pool?: IPoolOptions; /** * A list of schema for measurements in the database. */ schema?: ISchemaOptions[]; } export interface IPoint { /** * Measurement is the Influx measurement name. */ measurement?: string; /** * Tags is the list of tag values to insert. */ tags?: { [name: string]: string; }; /** * Fields is the list of field values to insert. */ fields?: { [name: string]: any; }; /** * Timestamp tags this measurement with a date. This can be a Date object, * in which case we'll adjust it to the desired precision, or a numeric * string or number, in which case it gets passed directly to Influx. */ timestamp?: Date | string | number; } export interface IParsedPoint extends IPoint { /** * Fields Pairs is the list of key/value pairs for each field on the point */ fieldsPairs: Array<[string, string]>; /** * Tags Names is the list of tag names in the point */ tagsNames: string[]; /** * Casted Timestamp is the timestamp value after being casted to the * desired precision. Default 'n' */ castedTimestamp?: string; } export interface IWriteOptions { /** * Precision at which the points are written, defaults to nanoseconds 'n'. */ precision?: grammar.TimePrecision; /** * Retention policy to write the points under, defaults to the DEFAULT * database policy. */ retentionPolicy?: string; /** * Database under which to write the points. This is required if a default * database is not provided in Influx. */ database?: string; } export interface IQueryOptions { /** * Defines the precision at which to query points. When left blank, it will * query in nanosecond precision. */ precision?: grammar.TimePrecision; /** * Retention policy to query from, defaults to the DEFAULT * database policy. */ retentionPolicy?: string; /** * Database under which to query the points. This is required if a default * database is not provided in Influx. */ database?: string; /** * Any placeholders used by the query. Using these is strongly recommended * to avoid injection attacks. */ placeholders?: Record; } export interface IParseOptions { /** * Precision at which the points are written, defaults to nanoseconds 'n'. */ precision?: grammar.TimePrecision; /** * Database under which to write the points. This is required if a default * database is not provided in Influx. */ database?: string; } /** * IRetentionOptions are passed into passed into the {@link * InfluxDB#createRetentionPolicy} and {@link InfluxDB#alterRetentionPolicy}. * See the [Downsampling and Retention page](https://docs.influxdata.com/ * influxdb/v1.0/guides/downsampling_and_retention/) on the Influx docs for * more information. */ export interface IRetentionOptions { database?: string; duration: string; replication: number; isDefault?: boolean; } /** * InfluxDB is the public interface to run queries against your database. * This is a 'driver-level' module, not a a full-fleged ORM or ODM; you run * queries directly by calling methods on this class. * * Please check out some of [the tutorials](https://node-influx.github.io/manual/tutorial.html) * if you want help getting started! * * @example * const Influx = require('influx'); * const influx = new Influx.InfluxDB({ * host: 'localhost', * database: 'express_response_db', * schema: [ * { * measurement: 'response_times', * fields: { * path: Influx.FieldType.STRING, * duration: Influx.FieldType.INTEGER * }, * tags: [ * 'host' * ] * } * ] * }) * * @example * // Connect over HTTPS * const Influx = require('influx'); * const influx = new Influx.InfluxDB({ * host: 'myinfluxdbhost', * port: 443, * protocol: 'https' * database: 'express_response_db', * schema: [ * { * measurement: 'response_times', * fields: { * path: Influx.FieldType.STRING, * duration: Influx.FieldType.INTEGER * }, * tags: [ * 'host' * ] * } * ] * }) * * influx.writePoints([ * { * measurement: 'response_times', * tags: { host: os.hostname() }, * fields: { duration, path: req.path }, * } * ]).then(() => { * return influx.query(` * select * from response_times * where host = $ * order by time desc * limit 10 * `, { * placeholders: { * host: os.hostname() * } * }) * }).then(rows => { * rows.forEach(row => console.log(`A request to ${row.path} took ${row.duration}ms`)) * }) */ export declare class InfluxDB { /** * Connect pool for making requests. * @private */ private readonly _pool; /** * Config options for Influx. * @private */ private readonly _options; /** * Map of Schema instances defining measurements in Influx. * @private */ private _schema; constructor(options: ISingleHostConfig); /** * Connect to an InfluxDB cluster by specifying a * set of connection options. */ constructor(options: IClusterConfig); /** * Connect to an InfluxDB instance using a configuration URL. * @example * new InfluxDB('http://user:password@host:8086/database') */ constructor(url: string); /** * Connects to a local, default Influx instance. */ constructor(); /** * Adds specified schema for better fields coercing. * * @param {ISchemaOptions} schema * @memberof InfluxDB */ addSchema(schema: ISchemaOptions): void; /** * Creates a new database with the provided name. * @param databaseName * @return * @example * influx.createDatabase('mydb') */ createDatabase(databaseName: string): Promise; /** * Deletes a database with the provided name. * @param databaseName * @return * @example * influx.dropDatabase('mydb') */ dropDatabase(databaseName: string): Promise; /** * Returns array of database names. Requires cluster admin privileges. * @returns a list of database names * @example * influx.getDatabaseNames().then(names => * console.log('My database names are: ' + names.join(', '))); */ getDatabaseNames(): Promise; /** * Returns array of measurements. * @returns a list of measurement names * @param [database] the database the measurement lives in, optional * if a default database is provided. * @example * influx.getMeasurements().then(names => * console.log('My measurement names are: ' + names.join(', '))); */ getMeasurements(database?: string): Promise; /** * Returns a list of all series within the target measurement, or from the * entire database if a measurement isn't provided. * @param [options] * @param [options.measurement] if provided, we'll only get series * from within that measurement. * @param [options.database] the database the series lives in, * optional if a default database is provided. * @returns a list of series names * @example * influx.getSeries().then(names => { * console.log('My series names in my_measurement are: ' + names.join(', ')) * }) * * influx.getSeries({ * measurement: 'my_measurement', * database: 'my_db' * }).then(names => { * console.log('My series names in my_measurement are: ' + names.join(', ')) * }) */ getSeries(options?: { measurement?: string; database?: string; }): Promise; /** * Removes a measurement from the database. * @param measurement * @param [database] the database the measurement lives in, optional * if a default database is provided. * @return * @example * influx.dropMeasurement('my_measurement') */ dropMeasurement(measurement: string, database?: string): Promise; /** * Removes a one or more series from InfluxDB. * * @returns * @example * // The following pairs of queries are equivalent: you can chose either to * // use our builder or pass in string directly. The builder takes care * // of escaping and most syntax handling for you. * * influx.dropSeries({ where: e => e.tag('cpu').equals.value('cpu8') }) * influx.dropSeries({ where: '"cpu" = \'cpu8\'' }) * // DROP SERIES WHERE "cpu" = 'cpu8' * * influx.dropSeries({ measurement: m => m.name('cpu').policy('autogen') }) * influx.dropSeries({ measurement: '"cpu"."autogen"' }) * // DROP SERIES FROM "autogen"."cpu" * * influx.dropSeries({ * measurement: m => m.name('cpu').policy('autogen'), * where: e => e.tag('cpu').equals.value('cpu8'), * database: 'my_db' * }) * // DROP SERIES FROM "autogen"."cpu" WHERE "cpu" = 'cpu8' */ dropSeries(options: b.measurement | b.where | { database: string; }): Promise; /** * Returns a list of users on the Influx database. * @return * @example * influx.getUsers().then(users => { * users.forEach(user => { * if (user.admin) { * console.log(user.user, 'is an admin!') * } else { * console.log(user.user, 'is not an admin!') * } * }) * }) */ getUsers(): Promise>; /** * Creates a new InfluxDB user. * @param username * @param password * @param [admin=false] If true, the user will be given all * privileges on all databases. * @return * @example * influx.createUser('connor', 'pa55w0rd', true) // make 'connor' an admin * * // make non-admins: * influx.createUser('not_admin', 'pa55w0rd') */ createUser(username: string, password: string, admin?: boolean): Promise; /** * Sets a password for an Influx user. * @param username * @param password * @return * @example * influx.setPassword('connor', 'pa55w0rd') */ setPassword(username: string, password: string): Promise; /** * Grants a privilege to a specified user. * @param username * @param privilege Should be one of 'READ' or 'WRITE' * @param [database] If not provided, uses the default database. * @return * @example * influx.grantPrivilege('connor', 'READ', 'my_db') // grants read access on my_db to connor */ grantPrivilege(username: string, privilege: "READ" | "WRITE", database?: string): Promise; /** * Removes a privilege from a specified user. * @param username * @param privilege Should be one of 'READ' or 'WRITE' * @param [database] If not provided, uses the default database. * @return * @example * influx.revokePrivilege('connor', 'READ', 'my_db') // removes read access on my_db from connor */ revokePrivilege(username: string, privilege: "READ" | "WRITE", database?: string): Promise; /** * Grants admin privileges to a specified user. * @param username * @return * @example * influx.grantAdminPrivilege('connor') */ grantAdminPrivilege(username: string): Promise; /** * Removes a admin privilege from a specified user. * @param username * @return * @example * influx.revokeAdminPrivilege('connor') */ revokeAdminPrivilege(username: string): Promise; /** * Removes a user from the database. * @param username * @return * @example * influx.dropUser('connor') */ dropUser(username: string): Promise; /** * Creates a continuous query in a database * @param name The query name, for later reference * @param query The body of the query to run * @param [database] If not provided, uses the default database. * @param [resample] If provided, adds resample policy * @return * @example * influx.createContinuousQuery('downsample_cpu_1h', ` * SELECT MEAN(cpu) INTO "7d"."perf" * FROM "1d"."perf" GROUP BY time(1m) * `, undefined, 'RESAMPLE FOR 7m') */ createContinuousQuery(name: string, query: string, database?: string, resample?: string): Promise; /** * Returns a list of continous queries in the database. * @param [database] If not provided, uses the default database. * @return * @example * influx.showContinousQueries() */ showContinousQueries(database?: string): Promise>; /** * Creates a continuous query in a database * @param name The query name * @param [database] If not provided, uses the default database. * @return * @example * influx.dropContinuousQuery('downsample_cpu_1h') */ dropContinuousQuery(name: string, database?: string): Promise; /** * Creates a new retention policy on a database. You can read more about * [Downsampling and Retention](https://docs.influxdata.com/influxdb/v1.0/ * guides/downsampling_and_retention/) on the InfluxDB website. * * @param name The retention policy name * @param options * @param [options.database] Database to create the policy on, * uses the default database if not provided. * @param options.duration How long data in the retention policy * should be stored for, should be in a format like `7d`. See details * [here](https://docs.influxdata.com/influxdb/v1.0/query_language/spec/#durations) * @param options.replication How many servers data in the series * should be replicated to. * @param [options.isDefault] Whether the retention policy should * be the default policy on the database. * @return * @example * influx.createRetentionPolicy('7d', { * duration: '7d', * replication: 1 * }) */ createRetentionPolicy(name: string, options: IRetentionOptions): Promise; /** * Alters an existing retention policy on a database. * * @param name The retention policy name * @param options * @param [options.database] Database to create the policy on, * uses the default database if not provided. * @param options.duration How long data in the retention policy * should be stored for, should be in a format like `7d`. See details * [here](https://docs.influxdata.com/influxdb/v1.0/query_language/spec/#durations) * @param options.replication How many servers data in the series * should be replicated to. * @param [options.default] Whether the retention policy should * be the default policy on the database. * @return * @example * influx.alterRetentionPolicy('7d', { * duration: '7d', * replication: 1, * default: true * }) */ alterRetentionPolicy(name: string, options: IRetentionOptions): Promise; /** * Deletes a retention policy and associated data. Note that the data will * not be immediately destroyed, and will hang around until Influx's * bi-hourly cron. * * @param name The retention policy name * @param [database] Database name that the policy lives in, * uses the default database if not provided. * @return * @example * influx.dropRetentionPolicy('7d') */ dropRetentionPolicy(name: string, database?: string): Promise; /** * Shows retention policies on the database * * @param [database] The database to list policies on, uses the * default database if not provided. * @return * @example * influx.showRetentionPolicies().then(policies => { * expect(policies.slice()).to.deep.equal([ * { * name: 'autogen', * duration: '0s', * shardGroupDuration: '168h0m0s', * replicaN: 1, * default: true, * }, * { * name: '7d', * duration: '168h0m0s', * shardGroupDuration: '24h0m0s', * replicaN: 1, * default: false, * }, * ]) * }) */ showRetentionPolicies(database?: string): Promise>; /** * Shows shards on the database * * @param [database] The database to list policies on, uses the * default database if not provided. * @return * @example * influx.showShards().then(shards => { * expect(shards.slice()).to.deep.equal([ * { * id: 1 * database: 'database', * retention_policy: 'autogen', * shard_group: 1, * start_time: '2019-05-06T00:00:00Z', * end_time: '2019-05-13T00:00:00Z', * expiry_time: '2019-05-13T00:00:00Z', * owners: null, * }, * ]) * }) */ showShards(database?: string): Promise>; /** * Drops a shard with the provided number. * @param shard_id * @return * @example * influx.dropShard(3) */ dropShard(shard_id: number): Promise; /** * WritePoints sends a list of points together in a batch to InfluxDB. In * each point you must specify the measurement name to write into as well * as a list of tag and field values. Optionally, you can specify the * time to tag that point at, defaulting to the current time. * * If you defined a schema for the measurement in the options you passed * to `new Influx(options)`, we'll use that to make sure that types get * cast correctly and that there are no extraneous fields or columns. * * For best performance, it's recommended that you batch your data into * sets of a couple thousand records before writing it. In the future we'll * have some utilities within node-influx to make this easier. * * --- * * A note when using manually-specified times and precisions: by default * we write using the `ms` precision since that's what JavaScript gives us. * You can adjust this. However, there is some special behaviour if you * manually specify a timestamp in your points: * - if you specify the timestamp as a Date object, we'll convert it to * milliseconds and manipulate it as needed to get the right precision * - if provide a INanoDate as returned from {@link toNanoTime} or the * results from an Influx query, we'll be able to pull the precise * nanosecond timestamp and manipulate it to get the right precision * - if you provide a string or number as the timestamp, we'll pass it * straight into Influx. * * Please see the IPoint and IWriteOptions types for a * full list of possible options. * * @param points * @param [options] * @return * @example * // write a point into the default database with * // the default retention policy. * influx.writePoints([ * { * measurement: 'perf', * tags: { host: 'box1.example.com' }, * fields: { cpu: getCpuUsage(), mem: getMemUsage() }, * } * ]) * * // you can manually specify the database, * // retention policy, and time precision: * influx.writePoints([ * { * measurement: 'perf', * tags: { host: 'box1.example.com' }, * fields: { cpu: getCpuUsage(), mem: getMemUsage() }, * timestamp: getLastRecordedTime(), * } * ], { * database: 'my_db', * retentionPolicy: '1d', * precision: 's' * }) */ writePoints(points: IPoint[], options?: IWriteOptions): Promise; /** * ParsePoint will perform the coercions/schema checks and return the data * required for writing a point. This will throw an error if a schema check * or coercion fails. This can be useful for flagging or "throwing out" bad * points in a batch write to prevent the entire batch from getting aborted * * --- * * A note when using this function, {@link InfluxDB#writePoints} will still perform * the same checks, so any pre-processed data will be checked for validity twice which * has potential performance implications on large data sets * * @param point * @param [options] * @return * @example * // parse a point as if it is getting written to the default * // databse with the default time precision * influx.parsePoint({ * measurement: 'perf', * tags: { host: 'box1.example.com' }, * fields: { cpu: getCpuUsage(), mem: getMemUsage() }, * }) * * // you can manually specify the database and time precision * influx.parsePoint({ * measurement: 'perf', * tags: { host: 'box1.example.com' }, * fields: { cpu: getCpuUsage(), mem: getMemUsage() }, * }, { * precision: 's', * database: 'my_db' * }) * * // if an error occurs, you can catch the error with try...catch * try { * influx.parsePoint({ * measurement: 'perf', * tags: { host: 'box1.example.com', myExtraneousTag: 'value' }, * fields: { cpu: getCpuUsage(), mem: getMemUsage(), myExtraneousField: 'value' }, * }) * } catch(err) { * handleError(err); * } */ parsePoint(point: IPoint, options?: IParseOptions): IParsedPoint; /** * WriteMeasurement functions similarly to {@link InfluxDB#writePoints}, but * it automatically fills in the `measurement` value for all points for you. * * @param measurement * @param points * @param [options] * @return * @example * influx.writeMeasurement('perf', [ * { * tags: { host: 'box1.example.com' }, * fields: { cpu: getCpuUsage(), mem: getMemUsage() }, * } * ]) */ writeMeasurement(measurement: string, points: IPoint[], options?: IWriteOptions): Promise; query(query: string[], options?: IQueryOptions): Promise>>; query(query: string, options?: IQueryOptions): Promise>; /** * QueryRaw functions similarly to .query() but it does no fancy * transformations on the returned data; it calls `JSON.parse` and returns * those results verbatim. * * @param query * @param [options] * @return * @example * influx.queryRaw('select * from perf').then(rawData => { * console.log(rawData) * }) */ queryRaw(query: string | string[], options?: IQueryOptions): Promise; /** * Pings all available hosts, collecting online status and version info. * @param timeout Given in milliseconds * @return * @example * influx.ping(5000).then(hosts => { * hosts.forEach(host => { * if (host.online) { * console.log(`${host.url.host} responded in ${host.rtt}ms running ${host.version})`) * } else { * console.log(`${host.url.host} is offline :(`) * } * }) * }) */ ping(timeout: number): Promise; /** * Returns the default database that queries operates on. It throws if called * when a default database isn't set. * @private */ private _defaultDB; /** * Creates options to be passed into the pool to query databases. * @private */ private _getQueryOpts; /** * Creates specified measurement schema * * @private * @param {ISchemaOptions} schema * @memberof InfluxDB */ private _createSchema; }