-
Notifications
You must be signed in to change notification settings - Fork 3
/
index_es6.js
77 lines (62 loc) · 2.06 KB
/
index_es6.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
'use strict'
var dgram = require('dgram')
var EventEmitter = require('events').EventEmitter
var util = require('util')
util.inherits(influx_line_udp, EventEmitter)
function influx_line_udp (host, port) {
var self = this
EventEmitter.call(self)
self.host = host
self.port = port
self.socket = dgram.createSocket('udp4')
return self
}
module.exports = influx_line_udp
influx_line_udp.prototype.send = function (mesurement, fields, tags={}, timestamp=undefined) {
let self = this
if (!mesurement || typeof mesurement !== 'string') {
return self.emit('error', 'mesurement should be string')
}
mesurement = escape(mesurement)
if (!fields || !isObject(fields)) {
return self.emit('error', 'fields should be an Object')
}
let escaped_fields_array = []
let unescaped_fields_keys = Object.keys(fields) || []
for (let i = 0; i < unescaped_fields_keys.length; i++) {
escaped_fields_array.push(escape(unescaped_fields_keys[i]) + '=' + fields[unescaped_fields_keys[i]])
}
let escaped_fields_str = escaped_fields_array.join(',')
let escapeTags = ''
if (!isObject(tags)) {
return self.emit('error', 'tags if provied should be an object')
}
let esapedTagsArray = []
for (let tagKey in tags) {
esapedTagsArray.push(escape(tagKey), escape(tags[tagKey]))
}
escapeTags = esapedTagsArray.join(',')
let data = `${mesurement}${escapeTags.length > 0 ? ',' + escapeTags : ''} ${escaped_fields_str}${timestamp ? ' ' + timestamp : timestamp}`
if (!self.socket) {
self.socket = dgram.createSocket('udp4')
}
_send(self.socket, data, 0, self.port, self.host)
}
function _send (socket, data, offset, port, host) {
if (!Buffer.isBuffer(data)) {
data = new Buffer(data)
}
socket.send(data, offset, data.length, port, host)
}
function isObject (obj) {
let type = typeof obj
return type === 'function' || type === 'object' && !!obj
}
function escape (str) {
return str.split('').map(function (character) {
if (character === ' ' || character === ',') {
character = '\\' + character
}
return character
}).join('')
}