Permalink
Browse files

[api] add convenience method `produce` to automatically add standard …

…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 da54e9162617a1ed5d8d0d16380c850a10c25382
Showing with 38 additions and 0 deletions.
  1. +38 −0 lib/godot/net/client.js
@@ -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,
@@ -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) {
@@ -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.

0 comments on commit da54e91

Please sign in to comment.