An open API service indexing awesome lists of open source software.

https://github.com/75lb/usage-stats

A minimal Google Analytics Measurement Protocol client for tracking statistics in shell and javascript applications
https://github.com/75lb/usage-stats

Last synced: over 1 year ago
JSON representation

A minimal Google Analytics Measurement Protocol client for tracking statistics in shell and javascript applications

Awesome Lists containing this project

README

          

[![view on npm](https://badgen.net/npm/v/usage-stats)](https://www.npmjs.org/package/usage-stats)
[![npm module downloads](https://badgen.net/npm/dt/usage-stats)](https://www.npmjs.org/package/usage-stats)
[![Gihub repo dependents](https://badgen.net/github/dependents-repo/75lb/usage-stats)](https://github.com/75lb/usage-stats/network/dependents?dependent_type=REPOSITORY)
[![Gihub package dependents](https://badgen.net/github/dependents-pkg/75lb/usage-stats)](https://github.com/75lb/usage-stats/network/dependents?dependent_type=PACKAGE)
[![Node.js CI](https://github.com/75lb/usage-stats/actions/workflows/node.js.yml/badge.svg)](https://github.com/75lb/usage-stats/actions/workflows/node.js.yml)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/feross/standard)

# usage-stats

A minimal, offline-friendly [Google Analytics Measurement Protocol](https://developers.google.com/analytics/devguides/collection/protocol/v1/) client for tracking usage statistics in shell and javascript applications.

This is a low-level API client, it doesn't hold any opinion of how usage tracking should be done. If you're looking for a convention which leverages the power and flexibility of [Custom Metrics and Dimensions](https://support.google.com/analytics/answer/2709828?hl=en&ref_topic=2709827), take a look at [app-usage-stats](https://github.com/75lb/app-usage-stats). For the command line client see [usage-stats-cli](https://github.com/75lb/usage-stats-cli).

## Synopsis

The most trivial example.

```js
const UsageStats = require('usage-stats')
const usageStats = new UsageStats('UA-98765432-1', { an: 'example' })

usageStats.screenView('screen name')
usageStats.event('category', 'action')
usageStats.send()
```

More realistic usage in a server application:

```js
const UsageStats = require('usage-stats')
const usageStats = new UsageStats('UA-98765432-1', {
an: 'encode-video',
av: '1.0.0'
})

// start a new session
usageStats.start()

// user set two options..
usageStats.event('option', 'verbose-level', 'infinite')
usageStats.event('option', 'preset', 'iPod')

try {
// Begin. Track as a screenView.
usageStats.screenView('encoding')
beginEncoding(options)
} catch (err) {
// Exception tracking
usageStats.exception(err.message, true)
}

// finished - mark the session as complete
// and send stats (or store if offline).
usageStats.end().send()
```

## Protocol Parameters

See [here](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters) for the full list of Google Analytics Measurement Protocol parameters.

### Sent by default

All parameters are send on demand, beside this list.

* Operating System version (sent in the UserAgent)
* [Client ID](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#cid) (a random UUID, generated once per OS user and stored)
* [Language](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ul) (`process.env.LANG`, if set)
* [Screen resolution](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#sr) (terminal rows by columns, by default)

## API Reference

**Kind**: Exported class
* [UsageStats](#exp_module_usage-stats--UsageStats) ⏏
* [new UsageStats(trackingId, [options])](#new_module_usage-stats--UsageStats_new)
* [.dir](#module_usage-stats--UsageStats.UsageStats+dir) : string
* [.defaults](#module_usage-stats--UsageStats.UsageStats+defaults) : Map
* [.start([sessionParams])](#module_usage-stats--UsageStats+start) ↩︎
* [.end([sessionParams])](#module_usage-stats--UsageStats+end) ↩︎
* [.disable()](#module_usage-stats--UsageStats+disable) ↩︎
* [.enable()](#module_usage-stats--UsageStats+enable) ↩︎
* [.event(category, action, [options])](#module_usage-stats--UsageStats+event) ⇒ Map
* [.screenView(name, [options])](#module_usage-stats--UsageStats+screenView) ⇒ Map
* [.exception([options])](#module_usage-stats--UsageStats+exception) ⇒ Map
* [.send([options])](#module_usage-stats--UsageStats+send) ⇒ Promise
* [.debug()](#module_usage-stats--UsageStats+debug) ⇒ Promise
* [.abort()](#module_usage-stats--UsageStats+abort) ↩︎

### new UsageStats(trackingId, [options])

| Param | Type | Description |
| --- | --- | --- |
| trackingId | string | Google Analytics tracking ID (required). |
| [options] | object | |
| [options.an] | string | App name |
| [options.av] | string | App version |
| [options.lang] | string | Language. Defaults to `process.env.LANG`. |
| [options.sr] | string | Screen resolution. Defaults to `${process.stdout.rows}x${process.stdout.columns}`. |
| [options.ua] | string | User Agent string to use. |
| [options.dir] | string | Path of the directory used for persisting clientID and queue. Defaults to `~/.usage-stats`. |
| [options.url] | string | Defaults to `'https://www.google-analytics.com/batch'`. |
| [options.debugUrl] | string | Defaults to `'https://www.google-analytics.com/debug/collect'`. |

**Example**
```js
const usageStats = new UsageStats('UA-98765432-1', {
an: 'sick app',
av: '1.0.0'
})
```

### usageStats.dir : string
Cache directory. Defaults to `~/.usage-stats`.

**Kind**: instance property of [UsageStats](#exp_module_usage-stats--UsageStats)

### usageStats.defaults : Map
A list of parameters to be to sent with every hit.

**Kind**: instance property of [UsageStats](#exp_module_usage-stats--UsageStats)
**Example**
```js
usageStats.defaults
.set('cd1', process.version)
.set('cd2', os.type())
.set('cd3', os.release())
.set('cd4', 'api')
```

### usageStats.start([sessionParams]) ↩︎
Starts the [session](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#sc).

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)
**Chainable**

| Param | Type | Description |
| --- | --- | --- |
| [sessionParams] | Array.<Map> | An optional map of paramaters to send with each hit in the sesison. |

### usageStats.end([sessionParams]) ↩︎
Ends the [session](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#sc).

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)
**Chainable**

| Param | Type | Description |
| --- | --- | --- |
| [sessionParams] | Array.<Map> | An optional map of paramaters to send with the final hit of this sesison. |

### usageStats.disable() ↩︎
Disable the module. While disabled, all operations are no-ops.

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)
**Chainable**

### usageStats.enable() ↩︎
Re-enable the module.

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)
**Chainable**

### usageStats.event(category, action, [options]) ⇒ Map
Track an event. All event hits are queued until `.send()` is called.

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)

| Param | Type | Description |
| --- | --- | --- |
| category | string | Event category (required). |
| action | string | Event action (required). |
| [options] | option | |
| [options.el] | string | Event label |
| [options.ev] | string | Event value |
| [options.hitParams] | Array.<map> | One or more additional params to send with the hit. |

### usageStats.screenView(name, [options]) ⇒ Map
Track a screenview. All screenview hits are queued until `.send()` is called. Returns the hit instance.

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)

| Param | Type | Description |
| --- | --- | --- |
| name | string | Screen name |
| [options] | object | |
| [options.hitParams] | Array.<map> | One or more additional params to set on the hit. |

### usageStats.exception([options]) ⇒ Map
Track a exception. All exception hits are queued until `.send()` is called.

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)

| Param | Type | Description |
| --- | --- | --- |
| [options] | object | optional params |
| [options.exd] | string | Error message |
| [options.exf] | boolean | Set true if the exception was fatal |
| [options.hitParams] | Array.<map> | One or more additional params to set on the hit. |

### usageStats.send([options]) ⇒ Promise
Send queued stats using as few requests as possible (typically a single request - a max of 20 events/screenviews may be sent per request). If offline, the stats will be stored and re-tried on next invocation.

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)
**Fulfil**: response[] - array of responses. Each response has `data` and the original node `res`.
**Reject**: Error - Rejects with the first error encountered. The error is a standard node http error with a `name` of `request-fail` and a `hits` property showing what failed to send.

| Param | Type |
| --- | --- |
| [options] | object |
| [options.timeout] | number |

### usageStats.debug() ⇒ Promise
Send any hits (including queued) to the GA [validation server](https://developers.google.com/analytics/devguides/collection/protocol/v1/validating-hits), fulfilling with the result.

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)
**Fulfil**: Response[]
**Reject**: Error - Error instance includes `hits`.

### usageStats.abort() ↩︎
Aborts the in-progress .send() operation, queuing any unsent hits.

**Kind**: instance method of [UsageStats](#exp_module_usage-stats--UsageStats)
**Chainable**

* * *

© 2016-23 Lloyd Brookes \<75pound@gmail.com\>. Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).