Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
75 lines (60 loc) · 1.51 KB
/
Copy pathindex.js
File metadata and controls
75 lines (60 loc) · 1.51 KB
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
const express = require("express");
const { createFeaturevisor } = require("@featurevisor/sdk");
/**
* Constants
*/
const PORT = 3000;
const DATAFILE_URL =
process.env.environment === "production"
? "https://featurevisor-example-cloudflare.pages.dev/production/featurevisor-tag-all.json"
: "https://featurevisor-example-cloudflare.pages.dev/staging/featurevisor-tag-all.json";
/**
* Featurevisor instance
*/
const f = createFeaturevisor({});
/**
* Express app with middleware
*/
const app = express();
app.use((req, res, next) => {
req.f = f;
next();
});
function evaluateMessage(instance = f) {
const featureKey = "baz";
const context = { userId: "user-123" };
return instance.isEnabled(featureKey, context)
? "Hello World!"
: "Not enabled yet!";
}
/**
* Routes
*/
app.get("/", (req, res) => {
res.send(evaluateMessage(req.f));
});
/**
* Start the server
*/
async function start() {
try {
const response = await fetch(DATAFILE_URL);
if (!response.ok) {
throw new Error(`Failed to fetch datafile: HTTP ${response.status}`);
}
const datafile = await response.json();
if (!f.setDatafile(datafile, true)) {
throw new Error("Datafile was rejected");
}
return app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
} catch (error) {
console.error("Error fetching datafile:", error);
process.exitCode = 1;
}
}
if (require.main === module) {
start();
}
module.exports = { app, evaluateMessage, start };