UNPKG

influx-point-formatter

Version:
89 lines (88 loc) 2.97 kB
"use strict"; /* eslint-disable @typescript-eslint/unified-signatures */ /* eslint-disable no-dupe-class-members */ Object.defineProperty(exports, "__esModule", { value: true }); const grammar = require("./grammar"); const schema_1 = require("./schema"); var grammar_1 = require("./grammar"); exports.FieldType = grammar_1.FieldType; exports.Precision = grammar_1.Precision; exports.Raw = grammar_1.Raw; exports.escape = grammar_1.escape; exports.toNanoDate = grammar_1.toNanoDate; const defaultOptions = Object.freeze({ schema: [] }); /** * Works similarly to Object.assign, but only overwrites * properties that resolve to undefined. */ function defaults(target, ...srcs) { srcs.forEach(src => { Object.keys(src).forEach((key) => { if (target[key] === undefined) { target[key] = src[key]; } }); }); return target; } class PointFormatter { constructor(options) { /** * Map of Schema instances defining measurements in Influx. * @private */ this._schema = Object.create(null); if (!options) { options = {}; } const resolved = options; this._options = defaults(resolved, defaultOptions); this._options.schema.forEach(schema => this._createSchema(schema)); } /** * Adds specified schema for better fields coercing. * * @param {ISchemaOptions} schema * @memberof PointFormatter */ addSchema(schema) { this._createSchema(schema); } /** * Formats a point in the InfluxDB line protocol format. * @param point * @param options */ formatPoint(point, options = {}) { const { precision = 'n' } = options; const { fields = {}, tags = {}, measurement, timestamp } = point; const schema = this._schema[measurement]; const fieldsPairs = schema ? schema.coerceFields(fields) : schema_1.coerceBadly(fields); const tagsNames = schema ? schema.checkTags(tags) : Object.keys(tags); let payload = measurement; for (let tagsName of tagsNames) { payload += ',' + grammar.escape.tag(tagsName) + '=' + grammar.escape.tag(tags[tagsName]); } for (let i = 0; i < fieldsPairs.length; i += 1) { payload += (i === 0 ? ' ' : ',') + grammar.escape.tag(fieldsPairs[i][0]) + '=' + fieldsPairs[i][1]; } if (timestamp !== undefined) { payload += ' ' + grammar.castTimestamp(timestamp, precision); } return payload; } /** * Creates specified measurement schema * * @private * @param {ISchemaOptions} schema * @memberof PointFormatter */ _createSchema(schema) { this._schema[schema.measurement] = new schema_1.Schema(schema); } } exports.PointFormatter = PointFormatter;