File size: 1,974 Bytes
e4bf523
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"use strict";

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;