34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
import {FileUtils} from "../FileUtils";
|
|
import {StoreComponent} from "../StoreComponent";
|
|
import * as path from "node:path";
|
|
import * as fs from "node:fs";
|
|
|
|
export class ItemStorage {
|
|
private itemDir: string
|
|
|
|
constructor(itemDir: string) {
|
|
this.itemDir = itemDir;
|
|
FileUtils.prepareDirectoryFroWriting(this.itemDir);
|
|
}
|
|
|
|
storeItem(storedItems: StoreComponent[]) {
|
|
this.persistDeletedItems(storedItems);
|
|
storedItems.forEach(item => this.storeSingleItem(item))
|
|
}
|
|
|
|
private persistDeletedItems(existingItems: StoreComponent[]) {
|
|
const itemFiles = FileUtils.listFilesInDirectory(this.itemDir);
|
|
itemFiles.forEach(itemFile => {
|
|
const itemFileName = path.parse(path.basename(itemFile)).name
|
|
if(existingItems.find(item => item.fileName === itemFileName) == undefined) {
|
|
fs.unlinkSync(itemFile)
|
|
}
|
|
})
|
|
}
|
|
|
|
private storeSingleItem(item: StoreComponent) {
|
|
const completeItemFile = path.join(this.itemDir, item.fileName + ".json");
|
|
fs.writeFileSync(completeItemFile, item.jsonString, 'utf-8')
|
|
}
|
|
}
|