1 | "use strict"
|
2 |
|
3 | const debug = require("debug")("motif:config")
|
4 | const fs = require("fs")
|
5 | const path = require("path")
|
6 |
|
7 | const DAO = require("@motif/dao")
|
8 |
|
9 | class Config {
|
10 | get mode() {
|
11 | return this._mode
|
12 | }
|
13 |
|
14 | get port() {
|
15 | return this._config.port || 3000
|
16 | }
|
17 |
|
18 | get createDoc() {
|
19 | return this._config.createDoc || false
|
20 | }
|
21 |
|
22 | get docPath() {
|
23 | return this._config.swagger && this._config.swagger.docPath || "/doc"
|
24 | }
|
25 |
|
26 | get database() {
|
27 | return this._config.database || {}
|
28 | }
|
29 |
|
30 | get(name) {
|
31 | return this._config[name]
|
32 | }
|
33 |
|
34 | _parseConfig( options = {} ) {
|
35 | let { config } = options
|
36 | if (config) {
|
37 | return config
|
38 | }
|
39 |
|
40 | try {
|
41 | if (fs.existsSync(this._appPath + "/config/conf.d/config." + this._mode + ".json")) {
|
42 | const content = fs.readFileSync( this._appPath + "/config/conf.d/config." + this._mode + ".json" )
|
43 | return JSON.parse(content)
|
44 | }
|
45 | else if (fs.existsSync(this._appPath + "/data/config/conf.d/config." + this._mode + ".json")) {
|
46 | const content = fs.readFileSync( this._appPath + "/data/config/conf.d/config." + this._mode + ".json" )
|
47 | return JSON.parse(content)
|
48 | }
|
49 | }
|
50 | catch(e) {
|
51 | debug("parse config error", e)
|
52 | }
|
53 |
|
54 | return {}
|
55 | }
|
56 |
|
57 | _initialize() {
|
58 | return new Promise( async callback => {
|
59 |
|
60 | for (var key in this._connections) {
|
61 | let options = this._connections[key]
|
62 | await DAO.registerConnnection(key, options)
|
63 | }
|
64 |
|
65 | if (this._connectionOptions) {
|
66 | await DAO.registerConnnections(this._connectionOptions)
|
67 | }
|
68 |
|
69 | callback()
|
70 | })
|
71 | }
|
72 |
|
73 | constructor(options) {
|
74 | debug("config", options)
|
75 |
|
76 | const { mode } = options
|
77 | const appPath = path.resolve(process.env.PWD, ".")
|
78 |
|
79 | this._appPath = appPath
|
80 | this._mode = mode
|
81 | this._config = this._parseConfig( options )
|
82 | this._connections = {}
|
83 | this._connectionOptions = null
|
84 | }
|
85 |
|
86 | connection(key) {
|
87 | return DAO.connection(key)
|
88 | }
|
89 |
|
90 | registerConnnection(key, options) {
|
91 | this._connections[key] = options
|
92 | }
|
93 |
|
94 | registerConnnections(connectionOptions) {
|
95 | this._connectionOptions = connectionOptions
|
96 | }
|
97 | }
|
98 |
|
99 | module.exports = Config
|