UNPKG

@signalk/streams

Version:

Utilities for handling streams of Signal K data

42 lines (41 loc) 1.45 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const moment_1 = __importDefault(require("moment")); const stream_1 = require("stream"); function defaultGetMilliseconds(msg) { // 2014-08-15-16:00:00.083 return (0, moment_1.default)(msg.timestamp, 'YYYY-MM-DD-HH:mm:ss.SSS').valueOf(); } class TimestampThrottle extends stream_1.Transform { lastMsgMillis; offsetMillis = 0; getMilliseconds; constructor(options = {}) { super({ objectMode: true }); this.lastMsgMillis = Date.now(); this.getMilliseconds = options.getMilliseconds ?? defaultGetMilliseconds; } _transform(msg, encoding, done) { const msgMillis = this.getMilliseconds(msg); if (msgMillis < this.lastMsgMillis) { this.offsetMillis = Date.now() - msgMillis; } this.lastMsgMillis = msgMillis; const millisToCorrectSendTime = msgMillis - Date.now() + this.offsetMillis; if (millisToCorrectSendTime <= 0) { this.push(msg); done(); } else { const doPush = this.push.bind(this, msg); setTimeout(() => { doPush(); done(); }, millisToCorrectSendTime); } } } exports.default = TimestampThrottle;