feat: add history tracking

This commit is contained in:
2018-10-17 15:08:30 -07:00
parent def95cd838
commit b6b5c27ffc

30
src/lib/history.mjs Normal file
View 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' });
}
}