refactor: initialise data

This commit is contained in:
Carlos Valente
2024-07-05 21:19:14 +02:00
committed by Carlos Valente
parent dae32e89a3
commit 84792bc00d
31 changed files with 1031 additions and 545 deletions
@@ -1,61 +1,40 @@
import { Low } from 'lowdb';
import { JSONFile } from 'lowdb/node';
import { appStatePath, isTest } from '../../setup/index.js';
import { appStatePath, isProduction, isTest } from '../../setup/index.js';
import { isPath } from '../../utils/fileManagement.js';
import { consoleError } from '../../utils/console.js';
interface Config {
interface AppState {
lastLoadedProject?: string;
}
/**
* Manages Ontime's runtime memory between boots
*/
const adapter = new JSONFile<AppState>(appStatePath);
const config = new Low<AppState>(adapter, {});
class AppState {
private config: Low<Config>;
private pathToFile: string;
private didInit = false;
constructor(appStatePath: string) {
this.pathToFile = appStatePath;
const adapter = new JSONFile<Config>(this.pathToFile);
this.config = new Low<Config>(adapter, {});
}
private async init() {
await this.config.read();
await this.config.write();
this.didInit = true;
}
private async get(): Promise<Config> {
if (!this.didInit) {
await this.init();
}
await this.config.read();
return this.config.data;
}
async isLastLoadedProject(projectName: string): Promise<boolean> {
const lastLoaded = await this.getLastLoadedProject();
return lastLoaded === projectName;
}
async getLastLoadedProject(): Promise<string | undefined> {
const data = await this.get();
return data.lastLoadedProject;
}
async setLastLoadedProject(filename: string): Promise<void> {
if (isTest) return;
if (!this.didInit) {
await this.init();
}
this.config.data.lastLoadedProject = filename;
await this.config.write();
}
export async function isLastLoadedProject(projectName: string): Promise<boolean> {
const lastLoaded = await getLastLoadedProject();
return lastLoaded === projectName;
}
export const appStateProvider = new AppState(appStatePath);
export async function getLastLoadedProject(): Promise<string | undefined> {
// in test environment, we want to start the demo project
if (isTest) return;
await config.read();
return config.data.lastLoadedProject;
}
export async function setLastLoadedProject(filename: string): Promise<void> {
if (isTest) return;
if (!isProduction) {
if (isPath(filename)) {
consoleError(filename);
consoleError(new Error('setLastLoadedProject should not be called with a path').stack);
process.exit(0);
}
}
config.data.lastLoadedProject = filename;
await config.write();
}