feat: add history tracking
This commit is contained in:
30
src/lib/history.mjs
Normal file
30
src/lib/history.mjs
Normal file
@@ -0,0 +1,30 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export default class History {
|
||||
constructor() {
|
||||
this.filePath = path.resolve('data', 'history.json');
|
||||
try {
|
||||
const data = fs.readFileSync(this.filePath);
|
||||
this.db = data.length === 0 ? [] : JSON.parse(data);
|
||||
} catch (e) {
|
||||
this.db = [];
|
||||
}
|
||||
}
|
||||
|
||||
get(id) {
|
||||
return this.db.find(doc => parseInt(doc.id, 10) === parseInt(id, 10));
|
||||
}
|
||||
|
||||
add(doc) {
|
||||
// prevent duplicate entries
|
||||
if (this.get(doc.id)) return;
|
||||
|
||||
// add doc to history, truncate as needed
|
||||
this.db.push(doc);
|
||||
if (this.db.length > 1000) this.db.splice(0, 1000);
|
||||
|
||||
// write the updated content to the file
|
||||
fs.writeFileSync(this.filePath, JSON.stringify(this.db), { encoding: 'utf8' });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user