feat: add data generation logic and history file class
This commit is contained in:
82
backend/classes/HistoryFile.js
Normal file
82
backend/classes/HistoryFile.js
Normal file
@@ -0,0 +1,82 @@
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
export default class HistoryFile {
|
||||
constructor(fileName) {
|
||||
this.path = path.join(process.cwd(), fileName);
|
||||
this.history = [];
|
||||
this.load();
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes history to file
|
||||
* @returns {boolean} true if successful, false otherwise
|
||||
*/
|
||||
writeToFile() {
|
||||
try {
|
||||
fs.writeFileSync(this.path, JSON.stringify(this.history));
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Failed to write data to history file: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads history file, and returns it as JSON
|
||||
* @returns {array}
|
||||
*/
|
||||
readFromFile() {
|
||||
try {
|
||||
const raw = fs.readFileSync(this.path, 'utf-8');
|
||||
return JSON.parse(raw);
|
||||
} catch (err) {
|
||||
console.warn(`Failed at reading history, using empty history: ${err.message}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads history file, if it exists
|
||||
* If not, creates empty file
|
||||
*/
|
||||
load() {
|
||||
if (fs.existsSync(this.path)) {
|
||||
// Read file, and update this.history
|
||||
const data = this.readFromFile();
|
||||
this.history = data;
|
||||
} else {
|
||||
// Create empty history file, if doesn't exist
|
||||
this.writeToFile();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves most recent 15 entries to history file
|
||||
*/
|
||||
save() {
|
||||
// If there's more than 15 entries, we need to save only most recent 15 ones
|
||||
if (this.history.length > 15) {
|
||||
this.history = this.history.slice(this.history.length - 15);
|
||||
}
|
||||
|
||||
// Write to history file
|
||||
this.writeToFile();
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends new entry to history file
|
||||
* Returns most recent entry
|
||||
* @param {number} number
|
||||
* @returns {object}
|
||||
*/
|
||||
append(number) {
|
||||
const data = { number, timestamp: Date.now() };
|
||||
// Push new entry to history
|
||||
this.history.push(data);
|
||||
// Save history file, and keep only 15 entries
|
||||
this.save();
|
||||
// Return most recent entry
|
||||
return data;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user