| 2 | import path from "path"; |
| 3 | |
| 4 | export default class StorageSubsystem { |
| 5 | public static readonly DATA_PATH = path.normalize(path.join(process.cwd(), "data")); |
| 6 | public static readonly INDEX_PATH = path.normalize(path.join(process.cwd(), "data", "index")); |
| 7 | |
| 8 | private checkFileName(name: string) { |
| 9 | if (!name) return false; |
| 10 | const blackList = ["\\", "/", ".."]; |
| 11 | for (const ch of blackList) { |
| 12 | if (name.includes(ch)) return false; |
| 13 | } |
| 14 | return true; |
| 15 | } |
| 16 | |
| 17 | public writeFile(name: string, data: string) { |
| 18 | const targetPath = path.normalize(path.join(StorageSubsystem.DATA_PATH, name)); |
| 19 | fs.writeFileSync(targetPath, data, { encoding: "utf-8" }); |
| 20 | } |
| 21 | |
| 22 | public readFile(name: string) { |
| 23 | const targetPath = path.normalize(path.join(StorageSubsystem.DATA_PATH, name)); |
| 24 | return fs.readFileSync(targetPath, { encoding: "utf-8" }); |
| 25 | } |
| 26 | |
| 27 | public readDir(dirName: string) { |
| 28 | const targetPath = path.normalize(path.join(StorageSubsystem.DATA_PATH, dirName)); |
| 29 | if (!fs.existsSync(targetPath)) return []; |
| 30 | const files = fs.readdirSync(targetPath).map((v) => path.normalize(path.join(dirName, v))); |
| 31 | return files; |
| 32 | } |
| 33 | |
| 34 | public deleteFile(name: string) { |
| 35 | const targetPath = path.normalize(path.join(StorageSubsystem.DATA_PATH, name)); |
| 36 | fs.removeSync(targetPath); |
| 37 | } |
| 38 | |
| 39 | public fileExists(name: string) { |
| 40 | const targetPath = path.normalize(path.join(StorageSubsystem.DATA_PATH, name)); |
| 41 | return fs.existsSync(targetPath); |
| 42 | } |
| 43 | |
| 44 | // Stored in local file based on class definition and identifier |
| 45 | public store(category: string, uuid: string, object: any) { |
| 46 | const dirPath = path.join(StorageSubsystem.DATA_PATH, category); |
| 47 | if (!fs.existsSync(dirPath)) fs.mkdirsSync(dirPath); |
| 48 | if (!this.checkFileName(uuid)) |
| 49 | throw new Error(`UUID ${uuid} does not conform to specification`); |
| 50 | const filePath = path.join(dirPath, `${uuid}.json`); |
| 51 | const data = JSON.stringify(object, null, 4); |
| 52 | fs.writeFileSync(filePath, data, { encoding: "utf-8" }); |
| 53 | } |
| 54 | |
| 55 | // deep copy of the primitive type with the copy target as the prototype |
| 56 | protected defineAttr(target: any, object: any): any { |
| 57 | for (const v of Object.keys(target)) { |
| 58 | const objectValue = object[v]; |
| 59 | if (objectValue === undefined) continue; |
| 60 | if (objectValue instanceof Array) { |
| 61 | target[v] = objectValue; |
nothing calls this directly
no outgoing calls
no test coverage detected