Class: TimestampedCounter

TimestampedCounter(metrics, key, options)

A timestamped event counter.

The timestamped counter stores one or more Redis keys based on the given event name and time granularity appends a timestamp to the key before storing the key in Redis. The counter can then report an overall aggregated count or a specific count for a time range, depending on the chosen granularity of the timestamp.

If no time granularity is chosen at creation time, the counter will work just like a global counter for the given key, i.e. events will not be timestamped.

Notice: The constructor for this class is usually not called directly but through the RedisMetrics#counter function.

Constructor

new TimestampedCounter(metrics, key, options)

Parameters:
Name Type Description
metrics RedisMetrics

An instance of a RedisMetrics client.

key string

The base key to use for this counter.

options Object

The options to use for this counter. The available options are specified in RedisMetrics#counter.

Source:

Methods

count(timeGranularityopt, eventObjopt, callbackopt) → {Promise}

Returns the current count for this counter.

If a specific time granularity is given, the value returned is the current value at the given granularity level. Effectively, this provides a single answer to questions such as "what is the count for the current day".

Notice: Counts cannot be returned for a given time granularity if it was not incremented at this granularity level in the first place.

Parameters:
Name Type Attributes Default Description
timeGranularity module:constants~timeGranularities <optional>
'total'

The granularity level to report the count for.

eventObj string | object <optional>

The event object. See TimestampedCounter#incr for more info on event objects.

callback function <optional>

Optional callback.

Since:
  • 0.1.0
Source:
Returns:

A promise that resolves to the result from Redis. Can be used instead of the callback function.

Type
Promise
Examples
myCounter.count((err, result) => {
  console.log(result); // Outputs the global count
});
myCounter.count('year', (err, result) => {
  console.log(result); // Outputs the count for the current year
});
myCounter.count('year', '/foo.html', (err, result) => {
  // Outputs the count for the current year for the event object '/foo.html'
  console.log(result);
});

countRange(timeGranularity, startDate, endDateopt, eventObjopt, callbackopt) → {Promise}

Returns an object mapping timestamps to counts in the given time range at a specific time granularity level.

Notice: This function does not make sense for the "none" time granularity.

Parameters:
Name Type Attributes Default Description
timeGranularity module:constants~timeGranularities

The granularity level to report the count for.

startDate Date | Object | string | number

Start date for the range (inclusive). Accepts the same argument as the constructor of a moment date.

endDate Date | Object | string | number <optional>
new Date()

End date for the range (inclusive). Accepts the same arguments as the constructor of a moment date.

eventObj string | object <optional>

The event object. See TimestampedCounter#incr for more info on event objects.

callback function <optional>

Optional callback.

Since:
  • 0.1.0
Source:
Returns:

A promise that resolves to the result from Redis. Can be used instead of the callback function.

Type
Promise

getKeys(timeopt, timeGranularityopt) → {Array}

Return a list of Redis keys that are associated with this counter at the current point in time (default) and will be written to Redis.

Parameters:
Name Type Attributes Default Description
time Moment <optional>
now

A specific time to get keys for.

timeGranularity module:constants~timeGranularities <optional>

The granularity level to return keys for. The default is the granularity from the options.

Source:
Returns:
Type
Array

getKeyTTL(key) → {number}

Finds the configured time to live for the given key.

Parameters:
Name Type Description
key string

The full key (including timestamp) for the key to determine the ttl for.

Source:
Returns:

Number of seconds that the key should live.

Type
number

incr(eventObjopt, callbackopt) → {Promise}

Increments this counter with 1.

For some use cases, it makes sense to pass in an event object to get more precise statistics for a specific event. For example, when counting page views on a page, it makes sense to increment a counter per specific page. For this use case, the eventObj parameter is a good fit.

Parameters:
Name Type Attributes Description
eventObj Object | string <optional>

Extra event information used to determine what counter to increment.

callback function <optional>

Optional callback.

Since:
  • 0.1.0
Source:
Returns:

A promise that resolves to the results from Redis. Can be used instead of the callback function.

Type
Promise

incrby(amount, eventObjopt, callbackopt) → {Promise}

Increments this counter with the given amount.

Parameters:
Name Type Attributes Description
amount number

The amount to increment with.

eventObj Object | string <optional>

Extra event information used to determine what counter to increment. See TimestampedCounter#incr.

callback function <optional>

Optional callback.

Since:
  • 0.2.0
Source:
See:
Returns:

A promise that resolves to the results from Redis. Can be used instead of the callback function.

Type
Promise

top(timeGranularityopt, directionopt, startingAtopt, limitopt, callbackopt) → {Promise}

Returns the current top elements for this counter.

If a specific time granularity is given, the value returned is the current value at the given granularity level. Effectively, this provides a single answer to questions such as "what is the rank for the current day".

Parameters:
Name Type Attributes Default Description
timeGranularity module:constants~timeGranularities <optional>
'total'

The granularity level to report the rank for.

direction string <optional>
desc

Optional sort direction, can be "asc" or "desc"

startingAt integer <optional>
0

Optional starting row.

limit integer <optional>
-1

Optional number of results to return.

callback function <optional>

Optional callback.

Since:
  • 0.1.1
Source:
Returns:

A promise that resolves to the result from Redis. Can be used instead of the callback function.

Type
Promise
Examples
myCounter.top((err, result) => {
  console.log(result); // Outputs the global rank
});
myCounter.top('year', (err, result) => {
  console.log(result); // Outputs the rank for the current year
});

trimEvents(keepDirectionopt, limitopt, callbackopt) → {Promise}

Permanently remove event objects for this counter so only the top-N elements remain in either descending (the default) or ascending order.

The event objects are removed with Redis' removal by rank for sorted sets (ZREMRANGEBYRANK).

The removal happens at each granularity level and only supports daily granularity and above (month, year, total) to optimize for the number of Redis keys to consider. It removes data going 5 years back in time.

If the function is used too often, there is a risk that the top-N elements will stay the same forever, because lower-ranking elements get removed before their scores have a change to increase.

Therefore, the function should only be used to try and reclaim space for big counters with a lot of event objects, and only rarely used.

Parameters:
Name Type Attributes Default Description
keepDirection string <optional>
desc

Sort direction for the top-N elements to keep, can be "asc" or "desc".

limit integer <optional>
1000

Number of results to keep.

callback function <optional>

Callback

Since:
  • 1.1.0
Source:
Returns:

Resolves when the values have been removed.

Type
Promise
Examples
// Keeps the top-5 elements with highest score
myCounter.trimEvents('desc', 5)
// Keeps the top-5 elements with lowest score
myCounter.trimEvents('asc', 5)