import fs from "fs"; export class Records { constructor(records = {}) { if (typeof records.records === "object") for (const [ key, value ] of Object.entries(records.records)) { const oldTableMatches = key.match(/^monthly_total_(\d{4})-(\d{2})$/); if (oldTableMatches) { const year = oldTableMatches[1]; const month = oldTableMatches[2]; if (!this.monthlyTotals) this.monthlyTotals = {}; if (!this.monthlyTotals[year]) this.monthlyTotals[year] = {}; this.monthlyTotals[year][month] = value; } else if (key === "record_calls" && typeof value === "object" && value !== null) this.callRecord = new CallRecord(value.date, value.count); else if (key === "total_calls_ever_placed" && typeof value === "number") this.totalCallsEverPlaced = value; else throw new Error(`Unknown legacy record key: ${key}`); } else for (const [ key, value ] of Object.entries(records)) this[key] = value; } static fromJSONFile(path) { const data = fs.readFileSync(path, "utf-8"); const obj = JSON.parse(data); return new Records(obj); } toJSONFile(path) { const data = JSON.stringify(this, null, 2); fs.writeFileSync(path, data, "utf-8"); } /** * @type {CallRecord} */ callRecord; /** * @type {number} */ totalCallsEverPlaced; /** * @type {{[year: string]: {[month: string]: number}}} */ monthlyTotals; } export class CallRecord { constructor(date, count) { this.date = date; this.count = count; } /** * @type {string} YYYY-MM-DD */ date; /** * @type {number} */ count; } // test (mjs) if (import.meta.url === `file://${process.argv[1]}`) { const records = Records.fromJSONFile("records.json"); console.log(records); console.log(JSON.stringify(records, null, 2)); }