diff --git a/README.md b/README.md index 5fced20..e6c3076 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,11 @@ If you want to set User Id you can add it into options: ```javascript var visitor = ua('UA-XXXX-XX', {uid: 'as8eknlll'}); ``` +If you want to only use `uid` to identify user and not using the clientID, just include the options `identifyByUserId: true`. This is useful for those who mainly track user base on UserId. +```javascript +var visitor = ua('UA-XXXX-XX', {uid: 'as8eknlll', identifyByUserId: true}); +``` + [see about User Id](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#uid) diff --git a/lib/index.js b/lib/index.js index 3cc4484..83c7ab3 100644 --- a/lib/index.js +++ b/lib/index.js @@ -54,7 +54,9 @@ var Visitor = module.exports.Visitor = function (tid, cid, options, context, per this._persistentParams = persistentParams || {}; this.tid = tid || this.options.tid; - this.cid = this._determineCid(cid, this.options.cid, (this.options.strictCidFormat !== false)); + if(!this.options.identifyByUserId || (this.options.identifyByUserId && !this.options.uid)) { + this.cid = this._determineCid(cid, this.options.cid, (this.options.strictCidFormat !== false)); + } if(this.options.uid) { this.uid = this.options.uid; } diff --git a/test/index.js b/test/index.js index 5bc78cb..e9e9313 100644 --- a/test/index.js +++ b/test/index.js @@ -114,6 +114,41 @@ describe("ua", function () { visitor.cid.should.equal(options.cid) }); + context("identifyByUserId", function() { + var uuidV4Spy + before(function() { + uuidV4Spy = sinon.spy(uuid, 'v4') + }) + after(function() { + uuidV4Spy.restore() + }) + afterEach(function() { + uuidV4Spy.reset() + }) + it("should not genereate cid if uid exists and identifyByUserId is true", function() { + var options = { + tid: "UA-XXXXX-XX", + uid: "some-user-id", + identifyByUserId: true + }; + + var visitor = ua(options); + uuidV4Spy.calledOnce.should.equal(false); + visitor.should.not.have.property("cid") + }); + + it("should still generate new cid (UUID) if identifyByUserId is true but uid does not exist", function () { + var options = { + tid: "UA-XXXXX-XX", + identifyByUserId: true + }; + + var visitor = ua(options); + uuidV4Spy.calledOnce.should.equal(true, "uuid.v4 should've been called once"); + utils.isUuid(visitor.cid).should.equal(true, "A valid random UUID should have been generated") + }); + }) + describe("params", function () {