feat: enhance history module
allow removing items, getting index instead of records, and unify the write methods
This commit is contained in:
@@ -15,8 +15,16 @@ export default class History {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get(id) {
|
persist() {
|
||||||
return this.db.find(doc => parseInt(doc.id, 10) === parseInt(id, 10));
|
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) {
|
add(doc) {
|
||||||
@@ -30,6 +38,18 @@ export default class History {
|
|||||||
if (this.db.length > MAX_ITEMS) this.db.splice(0, TRUNCATE_AMOUNT);
|
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' });
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user