Skip to content

Commit

Permalink
[api] add convenience method produce to automatically add standard …
Browse files Browse the repository at this point in the history
…default values to the object/array of objects passed to it then writes to the socket
  • Loading branch information
jcrugzz committed Nov 12, 2013
1 parent 2957a9d commit da54e91
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions lib/godot/net/client.js
Expand Up @@ -8,6 +8,7 @@
var dgram = require('dgram'),
net = require('net'),
utile = require('utile'),
ip = require('ip'),
clone = utile.clone,
back = require('back'),
EventEmitter = require('events').EventEmitter,
Expand Down Expand Up @@ -49,6 +50,14 @@ var Client = module.exports = function Client(options) {
data: {},
end: {}
};
this.defaults = {
host: ip.address(),
state: 'ok',
description: 'No Description',
tags: [],
metric: 1,
ttl: 15000
};

if (Array.isArray(options.producers)) {
options.producers.forEach(function (producer) {
Expand Down Expand Up @@ -126,6 +135,35 @@ Client.prototype.write = function (data) {
}
};

//
// ### function produce (data)
// #### @data {Object|Array} Data to write to socket with some extras
// Writes to a socket with some default values attached.
// This is purely a convenience method
//
Client.prototype.produce = function (data) {
var self = this;
//
// Add defaults to each object where a value does not already exist
//
function defaultify (obj) {
return Object.keys(self.defaults).reduce(function (acc, key) {
if (!acc[key]) { acc[key] = self.defaults[key] }
return acc;
}, obj);
}

//
// TODO: we may want to be monotonic here
//
this.defaults['time'] = Date.now();
data = !Array.isArray(data)
? defaultify(data)
: data.map(defaultify);

return this.write(data);
};

//
// ### function connect (callback)
// #### @port {Number} **Optional** Port number to connect on.
Expand Down

0 comments on commit da54e91

Please sign in to comment.