1 | const convict = require('convict')
|
2 | const log = require('@dadi/logger')
|
3 | const path = require('path')
|
4 | const schema = require('./schema')
|
5 |
|
6 | class Config {
|
7 | constructor() {
|
8 | this.instance = convict(schema)
|
9 | }
|
10 |
|
11 | filterUnauthenticatedProperties(node, configObject) {
|
12 | if (!node.properties) {
|
13 | return node.showToUnauthenticatedUsers ? configObject : null
|
14 | }
|
15 |
|
16 | let result
|
17 |
|
18 | Object.keys(node.properties).forEach(key => {
|
19 | const keyResult = this.filterUnauthenticatedProperties(
|
20 | node.properties[key],
|
21 | configObject[key]
|
22 | )
|
23 |
|
24 | if (keyResult) {
|
25 | result = result || {}
|
26 | result[key] = keyResult
|
27 | }
|
28 | })
|
29 |
|
30 | return result
|
31 | }
|
32 |
|
33 | getProperties({authenticated = false} = {}) {
|
34 | if (authenticated) {
|
35 | return this.instance.getProperties()
|
36 | }
|
37 |
|
38 | return this.filterUnauthenticatedProperties(
|
39 | this.instance.getSchema(),
|
40 | this.instance.getProperties()
|
41 | )
|
42 | }
|
43 |
|
44 | load(configPath) {
|
45 | const environment = this.instance.get('env')
|
46 | const filePath = path.join(configPath, `config.${environment}.json`)
|
47 |
|
48 | try {
|
49 | const data = require(filePath)
|
50 | const sanitisedData = this.sanitiseConfigData(data)
|
51 |
|
52 | this.instance.load(sanitisedData)
|
53 | this.instance.validate({})
|
54 | } catch (error) {
|
55 | log.error({module: 'config'}, error)
|
56 | }
|
57 | }
|
58 |
|
59 | sanitiseConfigData(inputData) {
|
60 | const data = {...inputData}
|
61 |
|
62 | if (data.apis && !data.api) {
|
63 | data.api = data.apis[0]
|
64 | data.apis = undefined
|
65 |
|
66 | const newSyntax = JSON.stringify({api: data.api}, null, 2)
|
67 |
|
68 | console.log(
|
69 | `The configuration file is using a legacy syntax for configuring the API. Please replace the "apis" property with:\n\n${newSyntax}`
|
70 | )
|
71 | }
|
72 |
|
73 | if (data.api.credentials) {
|
74 | data.api.credentials = undefined
|
75 |
|
76 | console.log(
|
77 | `The configuration file is using a legacy "credentials" block in the API configuration, which is deprecated. Please remove it from your configuration files.`
|
78 | )
|
79 | }
|
80 |
|
81 | return data
|
82 | }
|
83 | }
|
84 |
|
85 | const config = new Config()
|
86 |
|
87 | module.exports = config.instance
|
88 | module.exports.getUnauthenticated = () => {
|
89 | return config.getProperties({
|
90 | authenticated: false
|
91 | })
|
92 | }
|
93 |
|
94 | module.exports.initialise = configPath => {
|
95 | config.load(configPath)
|
96 | }
|