import Inject, { RegisterScoped } from "@entity-access/entity-access/dist/di/di.js"; import AppFile from "../../model/entities/AppFile.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; @RegisterScoped export default class FilePathService { @Inject db: SocialMailContext; async update(entity: AppFile) { const { db } = this; const { parentID, isFolder } = entity; if (parentID) { await db.appFiles.where(entity, (x, p) => x.appFileID === p.appFileID) .update((x) => ({ path: `${x.parent.path}${Sql.cast.asText(x.appFileID)}/` })); } else if (isFolder) { await db.appFiles.where(entity, (x, p) => x.appFileID === p.appFileID) .update((x) => ({ path: `${Sql.cast.asText(x.appFileID)}/` })); } else { return; } const stack = [[entity.appFileID]]; // there is no alternative other than enumerating all folders and // updating them.. for(;stack.length;) { const peek = stack.pop(); for(const id of peek) { const childFolders = await db.appFiles.where({ id }, (x, p) => x.parentID === p.id && x.isDeleted === false && x.isFolder === true) .map(({ appFileID }) => ({ appFileID})) .toArray(); const childIds = childFolders.map((x) => x.appFileID); if (childIds.length) { stack.push(childIds); } // update path for every files... await db.appFiles.where({ id }, (x, p) => x.parentID === p.id && x.isDeleted === false && x.path !== `${x.parent.path}${Sql.cast.asText(x.appFileID)}/` ) .update((x) => ({ path: `${x.parent.path}${Sql.cast.asText(x.appFileID)}/` })); } } } }