All files / piscosour/lib analytics.js

54.05% Statements 20/37
50% Branches 14/28
66.67% Functions 4/6
54.05% Lines 20/37
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    1x 1x 1x 1x 1x   1x         3x   3x             3x     3x         3x       1x 1x 1x                                 1x       1x 1x                 2x 1x   1x      
'use strict';
 
const config = require('./config');
const logger = require('./logger');
const params = require('./params');
const path = require('path');
const pkg = require(path.join(config.getDir('module'), 'package.json'));
 
module.exports = {
 
  _visitor: undefined,
 
  visitor: function() {
    const _config = config.get();
    let uuid;
    Iif (_config.recipes.userConfig
      && _config.recipes.userConfig.config
      && _config.recipes.userConfig.config.analytics
      && _config.recipes.userConfig.config.analytics.userok
      && _config.recipes.userConfig.config.analytics.userok[pkg.name]) {
      uuid = _config.recipes.userConfig.config.analytics.uuid;
    }
    Iif (params.uuid) {
      uuid = params.uuid;
    }
    Iif (_config.recipes.module.config.analytics
      && !this._visitor
      && uuid) {
      this._visitor = require('universal-analytics')(_config.recipes.module.config.analytics.id, uuid);
    }
    return this._visitor;
  },
 
  error: function(description, fatal, normal, exit) {
    const visitor = this.visitor();
    normal = normal ? normal : {};
    Iif (visitor) {
      if (!description) {
        description = 'No information';
      } else if (typeof description !== 'object') {
      } else {
        try {
          description = JSON.stringify(description);
        } catch (e) {
          description = description.args;
        }
      }
      logger.trace('#magenta', 'sending', '#red', 'ERROR', 'to google analytics');
      visitor.event(`Errors ${pkg.name} ${pkg.version}`, description, fatal ? 'FATAL' : 'CONTROLLED', {p: `/${pkg.name}/${pkg.version}/${normal.context}:${normal.name}`}, (err) => {
        this.notify(err);
        exit();
      });
    } else {
      exit();
    }
  },
  hit: function(url, pageName) {
    const visitor = this.visitor();
    Iif (visitor) {
      let page = `/${pkg.name}/${pkg.version}${url}`;
      logger.trace('#cyan', `sending ${page} to google analytics`);
      visitor.pageview(page, pkg.name, `${pageName} (${pkg.name} - ${pkg.version})`, (err) => {
        this.notify(err);
      });
    }
  },
  notify: function(err) {
    if (err) {
      logger.trace('#red', 'ERROR sending data to analytics', err);
    } else {
      logger.trace('data sent', '#green',  'OK', 'to analytics');
    }
  }
};