From 5e946213ba3968b6f8d4aacd078c145f9e225038 Mon Sep 17 00:00:00 2001 From: joe fleming Date: Tue, 19 Feb 2019 16:38:46 -0700 Subject: [PATCH] feat: enhance history module allow removing items, getting index instead of records, and unify the write methods --- src/lib/history.mjs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/lib/history.mjs b/src/lib/history.mjs index 9def930..204d823 100644 --- a/src/lib/history.mjs +++ b/src/lib/history.mjs @@ -15,8 +15,16 @@ export default class History { } } - get(id) { - return this.db.find(doc => parseInt(doc.id, 10) === parseInt(id, 10)); + 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) { @@ -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(); + } } }