-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
60 lines (53 loc) · 1.51 KB
/
app.js
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
require('dotenv').config()
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
app.get('/', (req, res) => {
res.send('<h1>Hello World!</h1>')
})
app.get('/unicorn', canUse('unicorn'), (req, res) => {
res.send('<h1>Hello Unicorns!</h1>')
})
app.get('/dragon', canUse('dragon'), (req, res) => {
res.send('<h1>Hello Dragons!</h1>')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
/**
* Get the feature config
* Features here are toggled on/off by an environment variable
* A more advanced check would have a user context and could check permissions or some user specific config
*
* @returns {{dragon: (string|boolean), unicorn: (string|boolean)}}
*/
function getFeatureConfig () {
return {
unicorn: process.env.ENABLE_FEATURE_UNICORN === 'true' || false,
dragon: process.env.ENABLE_FEATURE_DRAGON === 'true' || false
}
}
/**
* Checks the config to see if the feature is enabled
* @param feature
* @returns {boolean}
*/
function isFeatureEnabled(feature) {
return getFeatureConfig()[feature] === true
}
/**
* Controls if the feature should be executed or not
* @param feature
* @returns {(function(*, *, *): void)|*}
*/
function canUse (feature) {
return (req, res, next) => {
if (isFeatureEnabled(feature)) {
// If the feature is enabled then carry on and use it
next()
} else {
// If the feature is not enabled then return an error
res.status(404).send('<h1>Not found</h1>')
}
}
}