import { readFile, writeFile } from 'fs/promises'; import { getArg } from './lib/args.js'; import { error, log } from './lib/log.js'; import { userSchema, dbSchema } from './lib/schema.js'; const ctx = 'convertDb.js'; /** * Converts from array (v0) to current schema */ const fromV0 = (old) => { const userList = Object.fromEntries(old.map(e => [e.user, userSchema(e)])); return dbSchema(userList); } /** * Upgrades db versions */ const convertDb = async () => { log(ctx, 'Grabbing db'); let directory, db, updated; try { directory = getArg('path'); } catch (err) { error(ctx, err); return; } try { let file = await readFile(`${directory}/db.json`, { encoding: 'utf8' }); db = JSON.parse(file); } catch (err) { error(ctx, err); return; } log(ctx, 'Converting db'); if (Array.isArray(db)) { updated = fromV0(db); } else { updated = db; } log(ctx, 'Saving db'); try { await writeFile(`${directory}/db.json`, JSON.stringify(updated, null, 2)); await writeFile(`${directory}/db.bak.json`, JSON.stringify(db, null, 2)); } catch (err) { error(ctx, err); return; } log(ctx, 'Done'); } convertDb();