forked from evanshortiss/node-json-to-influx-line
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutil.js
123 lines (100 loc) · 2.5 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
'use strict';
var SPACE_REPLACER = [new RegExp(' ', 'gi'), '\\ '];
var COMMA_REPLACER = [new RegExp(',', 'gi'), '\\,'];
var EQUAL_REPLACER = [new RegExp('=', 'gi'), '\\='];
var FIELD_TAG_REPLACERS = [
SPACE_REPLACER,
COMMA_REPLACER,
EQUAL_REPLACER
];
var MEASURE_REPLACERS = [
SPACE_REPLACER,
COMMA_REPLACER
];
/**
* Certain chars need to be escaped for certain string portions.
* This function will escape the required items for a given input string
*
* @param {Array} replacers
* @param {String} input
* @return {String}
*/
function escapeChars (replacers, input) {
for (var r in replacers) {
input = input.replace(replacers[r][0], replacers[r][1]);
}
return input;
}
/**
* Creates a tag or value string that can be incldued in a complete InfluxDB
* line protocol string
* @param {Array} keys
* @param {Object} data
* @return {String}
*/
exports.generateTagString = function (data, keys) {
var ret = '';
// Keys can be provided. If not we assume all keys are required
keys = keys || Object.keys(data);
if (keys.length > 0) {
for (var i in keys) {
ret +=
escapeChars(FIELD_TAG_REPLACERS, keys[i]) +
'=' +
escapeChars(FIELD_TAG_REPLACERS, data[keys[i]]) +
',';
}
ret = ret.slice(0, -1);
}
return ret;
};
/**
* Creates a string of field values
* @param {Array} keys
* @param {Object} data
* @return {String}
*/
exports.generateFieldString = function (data, keys) {
var ret = '';
// Keys can be provided. If not we assume all keys are required
keys = keys || Object.keys(data);
if (keys.length > 0) {
for (var i in keys) {
ret += escapeChars(FIELD_TAG_REPLACERS, keys[i]) +
'=' +
data[keys[i]] +
',';
}
ret = ret.slice(0, -1);
}
return ret;
};
/**
* Generates a line protocol string from provided inputs
* @param {String} m measurement name
* @param {String} t tags
* @param {String} f fields
* @param {String} ts [timestamp]
* @return {String}
*/
exports.generateLineProtocolString = function (params) {
// timestamp is optional
if (params.ts) {
params.ts = ' ' + params.ts;
} else {
params.ts = '';
}
// tags are also optional, but we need to pad accordingly if they're missing
if (params.tags && params.tags.length !== 0) {
params.tags = ',' + params.tags;
} else {
params.tags = '';
}
return (
escapeChars(MEASURE_REPLACERS, params.measurement) +
params.tags +
' ' +
params.fields +
params.ts
);
};