Spaces:
Running
Running
| ; | |
| const fs = require("fs"); | |
| const path = require("path"); | |
| function _root() { | |
| if (global.config && global.config.folder_root) return global.config.folder_root; | |
| if (global.appl && global.appl.root) return global.appl.root; | |
| return process.cwd(); | |
| } | |
| function _safeRequire(filePath) { | |
| try { | |
| return require(filePath); | |
| } catch (e) { | |
| throw new Error( | |
| `[UtilityPrev.getModule] require failed: ${filePath}\n` + | |
| `- ${e && e.message ? e.message : e}` | |
| ); | |
| } | |
| } | |
| class UtilityPrev { | |
| getPath(...parts) { | |
| return path.resolve(_root(), path.join(...parts)); | |
| } | |
| getCustomPath(...parts) { | |
| const rel = path.join(...parts); | |
| const serviceName = global.config && global.config.service ? global.config.service.name : ""; | |
| const candidates = [ | |
| this.getPath("custom", serviceName, rel), | |
| this.getPath("custom", rel), | |
| this.getPath(rel) | |
| ]; | |
| for (const file of candidates) { | |
| if (fs.existsSync(file)) return path.resolve(file); | |
| } | |
| return path.resolve(this.getPath(rel)); | |
| } | |
| existFile(...parts) { | |
| const rel = path.join(...parts); | |
| const serviceName = global.config && global.config.service ? global.config.service.name : ""; | |
| const candidates = [ | |
| this.getPath("custom", serviceName, rel), | |
| this.getPath("custom", rel), | |
| this.getPath(rel) | |
| ]; | |
| return candidates.some((f) => fs.existsSync(f)); | |
| } | |
| getClass(...parts) { | |
| const filePath = this.getCustomPath(...parts); | |
| if (!fs.existsSync(filePath)) return null; | |
| return _safeRequire(filePath); | |
| } | |
| getModule(...parts) { | |
| if (!parts || parts.length === 0) { | |
| throw new Error("[UtilityPrev.getModule] empty arguments"); | |
| } | |
| const klass = this.getClass(...parts); | |
| if (klass == null) return null; | |
| if (typeof klass === "function") { | |
| try { | |
| return new klass(); | |
| } catch (_e) { | |
| return klass; | |
| } | |
| } | |
| return klass; | |
| } | |
| } | |
| module.exports = UtilityPrev; | |