From cc7c5968cbceecdb1a41fa1db2de3c154815bfdc Mon Sep 17 00:00:00 2001 From: joe fleming Date: Wed, 17 Oct 2018 15:08:30 -0700 Subject: [PATCH] feat: add history tracking --- src/lib/history.mjs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/lib/history.mjs diff --git a/src/lib/history.mjs b/src/lib/history.mjs new file mode 100644 index 0000000..1b1f939 --- /dev/null +++ b/src/lib/history.mjs @@ -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' }); + } +}