31 lines
757 B
JavaScript
31 lines
757 B
JavaScript
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' });
|
|
}
|
|
}
|