feat: enhance history module

allow removing items, getting index instead of records, and unify the write methods
This commit is contained in:
2019-02-19 16:38:46 -07:00
parent de77cd381b
commit 5e946213ba

View File

@@ -15,10 +15,18 @@ export default class History {
}
}
get(id) {
persist() {
fs.writeFileSync(this.filePath, JSON.stringify(this.db), { encoding: 'utf8' });
}
get(id, index = false) {
if (!index) {
return this.db.find(doc => parseInt(doc.id, 10) === parseInt(id, 10));
}
return this.db.findIndex(doc => parseInt(doc.id, 10) === parseInt(id, 10));
}
add(doc) {
// prevent duplicate entries
if (this.get(doc.id)) return;
@@ -30,6 +38,18 @@ export default class History {
if (this.db.length > MAX_ITEMS) this.db.splice(0, TRUNCATE_AMOUNT);
// write the updated content to the file
fs.writeFileSync(this.filePath, JSON.stringify(this.db), { encoding: 'utf8' });
this.persist();
}
remove(doc) {
const idx = this.get(doc.id, true);
// removing document at matched index
if (idx !== -1) {
this.db.splice(idx, 1);
// write the updated content to the file
this.persist();
}
}
}