@bazilio-san/af-stream
Version:
Data stream from database table
82 lines • 3.04 kB
JavaScript
import { DEBUG_LTR, TS_FIELD } from './constants';
import { millis2isoZ } from './utils/utils';
export class LastTimeRecords {
constructor(idFields) {
this.idFields = idFields;
this.set = new Set();
this.lastTs = null;
}
flush(ts = null) {
this.set = new Set();
this.lastTs = ts;
}
getKey(bufferRecord) {
return bufferRecord ? this.idFields.map((fieldName) => bufferRecord[fieldName]).join('|') : '';
}
getInfo4debug(bufferRecord) {
if (!(bufferRecord === null || bufferRecord === void 0 ? void 0 : bufferRecord[TS_FIELD])) {
return {};
}
const ts = bufferRecord[TS_FIELD];
const info = { ts, tsISO: millis2isoZ(ts) };
this.idFields.forEach((fName) => {
info[fName] = bufferRecord[fName];
});
return info;
}
fillLastTimeRecords(rb) {
var _a;
const currentLastTimeRecords = [];
if (!rb.length) {
return currentLastTimeRecords;
}
let index = rb.length;
const { lastTs } = this;
const ts = rb[index - 1][TS_FIELD];
if (lastTs !== ts) {
// There are records in the batch with new timestamps than the one in
// lastTimeRecords. This means lastTimeRecords must be reset.
this.flush(ts);
}
while (index > -1 && ((_a = rb[--index]) === null || _a === void 0 ? void 0 : _a[TS_FIELD]) === ts) {
const bufferRecord = rb[index];
const key = this.getKey(bufferRecord);
if (key) {
this.set.add(key);
// For debug
if (DEBUG_LTR) {
currentLastTimeRecords.push(this.getInfo4debug(bufferRecord));
}
}
}
return currentLastTimeRecords;
}
subtractLastTimeRecords(forBuffer) {
var _a;
const { lastTs, set } = this;
const subtractedLastTimeRecords = [];
if (!set.size || !forBuffer.length) {
return subtractedLastTimeRecords;
}
let index = -1;
while (((_a = forBuffer[++index]) === null || _a === void 0 ? void 0 : _a[TS_FIELD]) === lastTs) {
const key = this.getKey(forBuffer[index]);
if (key && set.has(key)) {
const removedRecord = forBuffer.splice(index, 1);
if (DEBUG_LTR) {
subtractedLastTimeRecords.push(this.getInfo4debug(removedRecord === null || removedRecord === void 0 ? void 0 : removedRecord[0]));
}
index--;
}
}
return subtractedLastTimeRecords;
}
getLtr() {
const { lastTs } = this;
const ts = (lastTs && (new Date(lastTs)).toISOString()) || '';
const hashes = [...this.set];
hashes.sort();
return { ts, hashes };
}
}
//# sourceMappingURL=LastTimeRecords.js.map