ConceptCreator/app/storage/storing/CharacterStorage.ts

36 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-03-22 10:01:47 +01:00
import {StoreComponent} from "../StoreComponent";
import {FileUtils} from "../FileUtils";
import * as path from "node:path";
import * as fs from "fs";
export class CharacterStorage {
private characterDir: string
constructor(characterDir: string) {
this.characterDir = characterDir;
FileUtils.prepareDirectoryFroWriting(characterDir)
}
storeCharacters(storedCharacters: StoreComponent[]) {
this.persistDeletedCharacters(storedCharacters)
storedCharacters.forEach(storedCharacter => this.storeSingleCharacter(storedCharacter))
}
private persistDeletedCharacters(existingCharacters: StoreComponent[]) {
const scriptAccountFiles = FileUtils.listFilesInDirectory(this.characterDir);
scriptAccountFiles.forEach(characterFile => {
const scriptAccountFileName = path.parse(path.basename(characterFile)).name
if(existingCharacters.find(character => character.fileName === scriptAccountFileName) == undefined) {
//No scriptAccountFile was found with that nae of the file. So the scriptAccount was deleted. Remove file
fs.unlinkSync(characterFile)
}
})
}
private storeSingleCharacter(character: StoreComponent) {
const completeScriptAccountFile = path.join(this.characterDir, character.fileName + ".json")
fs.writeFileSync(completeScriptAccountFile, character.jsonString, 'utf-8')
}
}