Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

refactor module #3

Closed
wants to merge 3 commits into from

2 participants

@andrewrk
  • simpler less error-prone code
  • ability to not console.log on error
  • add tests
  • documentation moved to readme for better accessibility
  • remove alias methods
  • default kissmetrics endpoint uses SSL
@andrewrk

If you merge this PR, Indaba Music will use your kissmetrics module and I will delete my fork. If you do not merge this PR, we will use my fork.

@glesperance
Owner

Hi Andrew,

Just looked at your fork and it definitely looks awesome.

However, I won't be merging it with the codebase as changing the whole code and all it's dependent libraries can hardly be considered a refactor.

If you've found some bugs and would like them to be fixed, please report them or have a specific pull request submitted.

In summary, I'm good with pull request provided it's not a complete re-write of the lib and that it respects the original idea behind it ; that is, using the same libraries as well as conforming to the same code writing style (jsDocs).

Cheers,

Gabriel

@glesperance glesperance closed this
@andrewrk

Cool. Least you could do is link to the fork in the README

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Feb 5, 2013
  1. @andrewrk

    refactor the module

    andrewrk authored
  2. @andrewrk

    add tests

    andrewrk authored
  3. @andrewrk

    update README

    andrewrk authored
This page is out of date. Refresh to see the latest.
View
106 README.md
@@ -1,24 +1,100 @@
-node-kissmetrics
-================
+# node-kissmetrics
-A KISSmetrics library for node.js
+KISSmetrics client for node.js
-Usage
------
+## Usage
-Basically, you simply create a new KM Client instance,
+```js
+// create a new KM Client instance:
+var Kissmetrics = require('kissmetrics');
+var kmClient = new Kissmetrics({ key: KM_KEY });
- var kissmestrics = require('kissmetrics')
- var kmClient = new kissmetrics({ key: KM_KEY });
+// record an event
+kmClient.event('blah@example.com', 'signed up');
+```
-and then issue commands using the provided methods,e.g.:
+## Documentation
- // Creating an alias
- kmClient.alias(km_ai_decoded || identity, [username, email], callback);
+### KissmetricsClient(options)
- // Recording an event
- kmClient.record(km_ai_decoded || identity, 'signed up', callback);
+KISSmetrics REST client constructor.
-etc.
+@param options {Object} The options object defining the REST client to
+instantiate. Its possible parameters are :
-For more information / documentation on how to use the methods, I suggest you take a look at the [source code](https://github.com/glesperance/node-kissmetrics/blob/master/lib/kissmetrics.js) ; all the methods are accompanied by proper jsDocs.
+@param key {String} your KISSmetrics API key.
+
+@param endpoint {String} (optional) The tracker endpoint to which the client
+connects to. Defaults to 'https://trk.kissmetrics.com'
+
+#### client.set(person, properties, [callback])
+
+Sets properties on a person without recording an event by making a request.
+
+@param person {String} The identity of the person.
+
+This is limited to 255 chars and all commas (,), and colons (:) will
+automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
+foo bar baz).
+
+@param properties {Object} An object containing the properties to be set on
+`person`.
+
+@param callback {Function} A function of the form `function(err)`.
+The default callback logs erroneous requests to stderr.
+
+#### client.alias(person, aliases, [callback])
+
+Aliases the user identified by `person` with `aliases`.
+
+@param person {String} The identity of the person.
+
+This is limited to 255 chars and all commas (,), and colons (:) will
+automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
+foo bar baz).
+
+@param alias | aliases {String|Array} The alias to apply to the person.
+
+This is limited to 255 chars and all commas (,), and colons (:) will
+automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
+foo bar baz).
+
+Can either be a string or an array of string if multiple alias are supplied.
+
+@param callback {Function} A callback of the form `function(err)`.
+The default callback logs erroneous requests to stderr.
+
+#### client.event(person, event, properties, [callback])
+
+Records `event` for `person. Also sets `properties` on the person if
+specified.
+
+@param person {String} The identity of the person doing the event.
+
+This is limited to 255 chars and all commas (,), and colons (:) will
+automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
+foo bar baz).
+
+@param event {String} The name of the event you want to record.
+
+This is limited to 255 chars and all commas (,), and colons (:) will
+automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
+foo bar baz).
+
+@param properties {Object} (optional) An object containing the properties to
+be set on `person`.
+
+@param callback {Function} A function of the form `function(err)`.
+The default callback logs erroneous requests to stderr.
+
+#### client.request(pathname, params, [callback])
+
+Performs the given request on the KISSmetrics tracker host.
+
+@param pathname {String} The path section of the URL, that comes after the
+host and before the query, including the initial slash if present.
+
+@param params {Object}
+
+@param callback {Function} A callback of the form `function(res)`.
+The default callback logs erroneous requests to stderr.
View
9 config.js
@@ -1,9 +0,0 @@
-function config() {
-
- this.DEFAULT_TRACKER_PORT = 80;
-
- this.DEFAULT_TRACKER_SERVER = 'trk.kissmetrics.com';
-
-}
-
-module.exports = new config;
View
71 index.js
@@ -0,0 +1,71 @@
+var superagent = require('superagent')
+ , Batch = require('batch')
+
+var DEFAULT_TRACKER_ENDPOINT = "https://trk.kissmetrics.com";
+
+module.exports = KissmetricsClient;
+
+function KissmetricsClient(options) {
+ options = options || {};
+ this.endpoint = options.endpoint || DEFAULT_TRACKER_ENDPOINT;
+ this.key = options.key;
+}
+
+KissmetricsClient.prototype.request = function(pathname, params, callback) {
+ callback = callback || defaultCallback;
+ var request = superagent.get(this.endpoint + pathname);
+ request.query(params);
+ request.query({
+ '_k': this.key,
+ '_d': 1,
+ '_t': params._t || Date.now(),
+ });
+ request.end(function (err, resp) {
+ if (err) {
+ callback(err);
+ } else if (! resp.ok) {
+ callback(new Error("kissmetrics http " + resp.status + " " + resp.text));
+ } else {
+ callback(null, resp);
+ }
+ });
+}
+
+KissmetricsClient.prototype.set = function(person, properties, callback) {
+ properties._p = person;
+ this.request('/s', properties, callback);
+}
+
+KissmetricsClient.prototype.alias = function(person, aliases, callback) {
+ var self = this;
+ aliases = Array.isArray(aliases) ? aliases : [aliases];
+
+ var batch = new Batch();
+ aliases.forEach(function(alias) {
+ batch.push(function(callback) {
+ var params = {
+ '_p': person,
+ '_n': alias,
+ };
+ self.request('/a', params, callback);
+ });
+ });
+ batch.end(callback);
+}
+
+KissmetricsClient.prototype.event = function(person, event, properties, callback) {
+ if (typeof properties === 'function') {
+ callback = properties;
+ properties = {};
+ }
+ properties = properties || {};
+
+ properties._p = person;
+ properties._n = event;
+
+ this.request('/e', properties, callback);
+}
+
+function defaultCallback(err) {
+ if (err) console.error("KISSmetrics error:", err.stack);
+}
View
1  kissmetrics.js
@@ -1 +0,0 @@
-module.exports = require('./lib/kissmetrics');
View
214 lib/kissmetrics.js
@@ -1,214 +0,0 @@
-var request = require('request')
- , async = require('async')
- ;
-
-var config = require('../config')
- , DEFAULT_TRACKER_SERVER = config.DEFAULT_TRACKER_SERVER
- , DEFAULT_TRACKER_PORT = config.DEFAULT_TRACKER_PORT
- ;
-
-/******************************************************************************
- * Performs the given request on the KISSmetrics tracker host.
- *
- * @param pathname {String} The path section of the URL, that comes after the
- * host and before the query, including the initial slash if present.
- *
- * @param query_params {Object}
- *
- * @param callback {Function} A callback of the form `function(res)`.
- *
- */
-function request_kissmetrics_client(pathname, query_params, callback) {
-
- var query_string = ['_k=', this.key, '&'].join('')
- , uri
- , v
- ;
-
- query_params['_t'] = (query_params['_d'] ? query_params['_t'] : Date.now());
-
- for(var k in query_params) {
-
- v = query_params[k];
-
- if (query_string !== '') {
- query_string += '&';
- }
-
- query_string += [k, v].join('=');
-
- }
-
- uri = encodeURI(['http', ':', '//', this.host, ':', this.port, pathname, '?', query_string].join(''));
-
- request({ uri: uri }, function (err, res) {
-
- if (err) {
-
- console.log('xxx KISSmetrics error');
- console.log(' uri : ' + uri);
- console.log(' error : ' + err.message);
-
- } else if (res.statusCode !== 200) {
- err = new Error('KISSmetrics error ---> RECEIVED WRONG STATUS CODE [' + res.statusCode + ']');
- }
-
- callback(err, res);
-
- });
-
-}
-
-kissmetrics_client.prototype.request = request_kissmetrics_client;
-
-/******************************************************************************
- * Sets properties on a person without recording an event by making a request.
- *
- * @param person {String} The identity of the person.
- *
- * This is limited to 255 chars and all commas (,), and colons (:) will
- * automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
- * foo bar baz).
- *
- * @param properties {Object} An object containing the properties to be set on
- * `person`.
- *
- * @param callback {Function} A function of the form `function(err)`.
- *
- */
-function set_kissmetrics_client(person, properties, callback) {
-
- var query_params = new Object(properties)
- ;
-
- query_params['_p'] = person;
-
- this.request('/s', query_params, callback);
-
-}
-
-kissmetrics_client.prototype.set = set_kissmetrics_client;
-kissmetrics_client.prototype.properties = set_kissmetrics_client;
-
-/******************************************************************************
- * Aliases the user identified by `person` with `aliases`.
- *
- * @param person {String} The identity of the person.
- *
- * This is limited to 255 chars and all commas (,), and colons (:) will
- * automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
- * foo bar baz).
- *
- * @param alias | aliases {String|Array} The alias to apply to the person.
- *
- * This is limited to 255 chars and all commas (,), and colons (:) will
- * automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
- * foo bar baz).
- *
- * Can either be a string or an array of string if multiple alias are supplied.
- *
- * @param callback {Function} A callback of the form `function(err)`.
- *
- */
-function alias_kissmetrics_client(person, aliases, callback) {
-
- var aliases = (Array.isArray(aliases) ? aliases : [aliases])
- , that = this
- ;
-
- async.forEach(
-
- aliases
-
- , function(alias, callback) {
-
- var query_params = {}
- ;
-
- query_params['_p'] = person;
- query_params['_n'] = alias;
-
- that.request('/a', query_params, callback);
-
- }
-
- , callback
-
- );
-
-}
-
-kissmetrics_client.prototype.alias = alias_kissmetrics_client;
-
-/******************************************************************************
- * Records `event` for `person. Also sets `properties` on the person if
- * specified.
- *
- * @param person {String} The identity of the person doing the event.
- *
- * This is limited to 255 chars and all commas (,), and colons (:) will
- * automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
- * foo bar baz).
- *
- * @param event {String} The name of the event you want to record.
- *
- * This is limited to 255 chars and all commas (,), and colons (:) will
- * automatically be changed to spaces (KISSmetrics will convert foo:bar,baz to
- * foo bar baz).
- *
- * @param properties {Object} (optional) An object containing the properties to
- * be set on `person`.
- *
- * @param callback {Function} A function of the form `function(err)`.
- */
-function record_kissmetrics_client() {
-
- var args = Array.prototype.slice.call(arguments)
-
- , callback = args.pop()
-
- , person = args.shift()
- , event = args.shift()
- , properties = args.shift() || {}
-
- , query_params = new Object(properties)
- ;
-
- query_params['_p'] = person;
- query_params['_n'] = event;
-
- this.request('/e', query_params, callback);
-
-}
-
-kissmetrics_client.prototype.record = record_kissmetrics_client;
-kissmetrics_client.prototype.event = record_kissmetrics_client;
-
-/******************************************************************************
- * KISSmetrics REST client constructor.
- *
- * @param options {Object} The options object defining the REST client to
- * instantiate. Its possible parameters are :
- *
- * @param key {String} your KISSmetrics API key.
- *
- * @param host {String} (optional) The tracker host to which the client must be
- * connected to. Defaults to 'trk.kissmetrics.com'
- *
- * @param port {Number} (optional) The port of the tracker to connect to.
- * Defaults to port 80
- *
- */
-function kissmetrics_client(options) {
-
- var options = options || {}
- ;
-
- this.host = options.host || DEFAULT_TRACKER_SERVER;
- this.port = options.port || DEFAULT_TRACKER_PORT;
-
- this.key = options.key;
-
-}
-
-module.exports = kissmetrics_client;
View
58 package.json
@@ -1,35 +1,31 @@
{
- "name": "kissmetrics"
-
-, "description": "Library for KISSmetrics REST API"
-
-, "keywords": ["kissmetrics", "kiss", "metrics","analytics", "REST", "API"]
-
-, "version": "0.0.4"
-
-, "homepage": "http://wavo.me"
-
-, "repository":
- { "type" : "git"
- , "url" : "git://github.com/glesperance/node-kissmetrics.git"
- }
-
-, "author": "Gabriel Lesperance <gabriel@wavo.me> (glesperance.com / wavo.me)"
-
-, "main": "kissmetrics"
-
-, "engines": {
+ "name": "kissmetrics",
+ "description": "KISSmetrics API client",
+ "keywords": [
+ "kissmetrics",
+ "kiss",
+ "metrics",
+ "analytics"
+ ],
+ "scripts": {
+ "test": "mocha --reporter spec"
+ },
+ "version": "0.0.4",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/glesperance/node-kissmetrics.git"
+ },
+ "author": "Gabriel Lesperance <gabriel@wavo.me>",
+ "main": "index.js",
+ "engines": {
"node": ">= 0.4.12"
+ },
+ "dependencies": {
+ "superagent": "~0.12.2",
+ "batch": "~0.2.1"
+ },
+ "license": "MIT",
+ "devDependencies": {
+ "mocha": "~1.8.1"
}
-
-, "dependencies": {
- "async" : ">= 0.1.10"
- , "request" : ">= 2.1.1"
- }
-
-, "licenses" :
- [{
- "type" : "MIT"
- , "url" : "https://github.com/glesperance/node-kissmetrics/raw/master/LICENSE"
- }]
}
View
32 test/test.js
@@ -0,0 +1,32 @@
+/*global describe:false, it:false, before:false */
+var Kissmetrics = require('../');
+
+var TEST_PORT = 50458;
+
+describe("Kissmetrics", function() {
+ var server;
+ var kmClient;
+ before(function(done) {
+ kmClient = new Kissmetrics({
+ key: "blah",
+ endpoint: "http://localhost:" + TEST_PORT,
+ });
+ server = require('http').createServer(function(req, resp) {
+ resp.statusCode = 200;
+ resp.end();
+ });
+ server.listen(TEST_PORT, done);
+ });
+ it("set", function(done) {
+ kmClient.set('person', {"foo": "bar"}, done);
+ });
+ it("alias", function(done) {
+ kmClient.alias('person2', ['alias1', 'alias2'], done);
+ });
+ it("event", function(done) {
+ kmClient.event('person3', "event name", done);
+ });
+ it("event with properties", function(done) {
+ kmClient.event('person3', "event name", {"hi": "yes"}, done);
+ });
+});
Something went wrong with that request. Please try again.