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' }); + } +}