All files / redis-smq-monitor-app/src/plugins/message-rate/common sorted-set-time-series.ts

92.85% Statements 26/28
78.57% Branches 11/14
100% Functions 8/8
96.15% Lines 25/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 6857x     57x   57x           29x 29x 29x   29x 20x 20x 20x 9x       22x 22x 22x 22x         136x             136x         136x   136x 136x 136x     7990x   7990x     7990x         136x              
import { TimeSeries } from './time-series';
import { TTimeSeriesParams, TTimeSeriesRange } from '../../../../types';
import { ICallback, TRedisClientMulti } from 'redis-smq-common/dist/types';
import { errors } from 'redis-smq-common';
 
export class SortedSetTimeSeries extends TimeSeries<TTimeSeriesParams> {
  add(
    ts: number,
    value: number,
    mixed: ICallback<void> | TRedisClientMulti,
  ): void {
    const process = (multi: TRedisClientMulti) => {
      multi.zadd(this.key, ts, `${value}:${ts}`);
      this.expireAfter && multi.expire(this.key, this.expireAfter);
    };
    if (typeof mixed === 'function') {
      const multi = this.redisClient.multi();
      process(multi);
      this.redisClient.execMulti(multi, (err) => mixed(err));
    } else process(mixed);
  }
 
  cleanUp(cb: ICallback<void>): void {
    const ts = TimeSeries.getCurrentTimestamp();
    const max = ts - this.retentionTime;
    this.redisClient.zremrangebyscore(this.key, '-inf', `${max}`, (err) =>
      cb(err),
    );
  }
 
  getRange(from: number, to: number, cb: ICallback<TTimeSeriesRange>): void {
    Iif (to <= from) {
      cb(
        new errors.ArgumentError(
          `Expected parameter [to] to be greater than [from]`,
        ),
      );
    } else {
      this.redisClient.zrangebyscorewithscores(
        this.key,
        to,
        from,
        (err, reply) => {
          Iif (err) cb(err);
          else {
            const replyRange = reply ?? {};
            const length = to - from;
            const range = new Array(length)
              .fill(0)
              .map((_: number, index: number) => {
                const timestamp = from + index;
                const value =
                  typeof replyRange[timestamp] === 'string'
                    ? Number(replyRange[timestamp].split(':')[0])
                    : 0;
                return {
                  timestamp,
                  value,
                };
              });
            cb(null, range);
          }
        },
      );
    }
  }
}