2024-12-03 11:11:44 +02:00
|
|
|
import { serviceSeqTrackerDb, type ServiceSeqTrackerDocument } from "./dbs";
|
2024-11-27 15:57:11 +02:00
|
|
|
|
|
|
|
|
export class ServiceSeqTracker {
|
2024-11-29 12:38:08 +02:00
|
|
|
/**
|
|
|
|
|
* @param _id
|
|
|
|
|
* @constructor
|
|
|
|
|
*/
|
|
|
|
|
static async Init(_id: string) {
|
2024-12-03 11:11:44 +02:00
|
|
|
const doc = await serviceSeqTrackerDb.get(_id).catch((error) => {
|
2024-11-27 15:57:11 +02:00
|
|
|
if (error.name === "not_found") {
|
|
|
|
|
return {
|
2024-11-29 12:38:08 +02:00
|
|
|
_id,
|
2024-11-27 15:57:11 +02:00
|
|
|
lastSeq: "0",
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
throw error; // Re-throw other errors
|
|
|
|
|
});
|
2024-12-03 11:11:44 +02:00
|
|
|
return new ServiceSeqTracker(doc);
|
2024-11-29 12:38:08 +02:00
|
|
|
}
|
2024-11-27 15:57:11 +02:00
|
|
|
|
2024-12-03 11:11:44 +02:00
|
|
|
private constructor(private doc: ServiceSeqTrackerDocument) {}
|
2024-11-27 15:57:11 +02:00
|
|
|
|
2024-11-29 12:38:08 +02:00
|
|
|
get lastSeq() {
|
2024-12-03 11:11:44 +02:00
|
|
|
return this.doc.lastSeq;
|
2024-11-27 15:57:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
checkNextSeq(seq: number | string) {
|
2024-12-03 11:11:44 +02:00
|
|
|
if (!this.doc) {
|
2024-11-29 12:38:08 +02:00
|
|
|
}
|
2024-11-27 15:57:11 +02:00
|
|
|
const next = parseInt(seq as string, 10);
|
2024-12-03 11:11:44 +02:00
|
|
|
const current = parseInt(this.doc.lastSeq as string, 10);
|
2024-11-27 15:57:11 +02:00
|
|
|
if (next < current) {
|
|
|
|
|
throw new Error(
|
|
|
|
|
`Sequence number is too old: ${seq} (${next} < ${current})`,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
saveSeq(seq: number | string) {
|
2024-12-03 11:11:44 +02:00
|
|
|
this.doc.lastSeq = seq;
|
|
|
|
|
return serviceSeqTrackerDb.put(this.doc);
|
2024-11-27 15:57:11 +02:00
|
|
|
}
|
|
|
|
|
}
|