fix: don't truncate all history when max is hit

truncate a smaller amount of the oldest entries
This commit is contained in:
2019-02-19 16:36:43 -07:00
parent d19ab86a68
commit bd42c4c415

View File

@@ -1,6 +1,9 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
const MAX_ITEMS = 1000; // max entries in history
const TRUNCATE_AMOUNT = 200; // count of entries to remove when max is hit
export default class History { export default class History {
constructor() { constructor() {
this.filePath = path.resolve('data', 'history.json'); this.filePath = path.resolve('data', 'history.json');
@@ -20,9 +23,11 @@ export default class History {
// prevent duplicate entries // prevent duplicate entries
if (this.get(doc.id)) return; if (this.get(doc.id)) return;
// add doc to history, truncate as needed // add doc to history
this.db.push(doc); this.db.push(doc);
if (this.db.length > 1000) this.db.splice(0, 1000);
// truncate as needed, removing first TRUNCATE_AMOUNT entries from the array
if (this.db.length > MAX_ITEMS) this.db.splice(0, TRUNCATE_AMOUNT);
// write the updated content to the file // write the updated content to the file
fs.writeFileSync(this.filePath, JSON.stringify(this.db), { encoding: 'utf8' }); fs.writeFileSync(this.filePath, JSON.stringify(this.db), { encoding: 'utf8' });