|
| 1 | +const express = require("express"); |
| 2 | +const { createInstance } = require("@featurevisor/sdk"); |
| 3 | + |
| 4 | +require("isomorphic-fetch"); |
| 5 | + |
| 6 | +/** |
| 7 | + * Constants |
| 8 | + */ |
| 9 | +const PORT = 3000; |
| 10 | +const REFRESH_INTERVAL = 60 * 5; // every 5 minutes |
| 11 | + |
| 12 | +const DATAFILE_URL = |
| 13 | + process.env.environment === "production" |
| 14 | + ? "https://featurevisor-example-cloudflare.pages.dev/production/datafile-tag-all.json" |
| 15 | + : "https://featurevisor-example-cloudflare.pages.dev/staging/datafile-tag-all.json"; |
| 16 | + |
| 17 | +/** |
| 18 | + * Featurevisor instance |
| 19 | + */ |
| 20 | +const f = createInstance({ |
| 21 | + datafileUrl: DATAFILE_URL, |
| 22 | + |
| 23 | + onReady: () => console.log(`Featurevisor SDK is now ready`), |
| 24 | + onRefresh: () => console.log(`Featurevisor SDK has refreshed`), |
| 25 | + onUpdate: () => console.log(`Featurevisor SDK has updates`), |
| 26 | + |
| 27 | + // optionally refresh the datafile every 5 minutes, |
| 28 | + // without having to restart the server |
| 29 | + refreshInterval: REFRESH_INTERVAL, |
| 30 | +}); |
| 31 | + |
| 32 | +/** |
| 33 | + * Express app with middleware |
| 34 | + */ |
| 35 | +const app = express(); |
| 36 | + |
| 37 | +app.use((req, res, next) => { |
| 38 | + req.f = f; |
| 39 | + next(); |
| 40 | +}); |
| 41 | + |
| 42 | +/** |
| 43 | + * Routes |
| 44 | + */ |
| 45 | +app.get("/", (req, res) => { |
| 46 | + const featureKey = "baz"; |
| 47 | + const context = { userId: "user-123" }; |
| 48 | + |
| 49 | + const isEnabled = f.isEnabled(featureKey, context); |
| 50 | + |
| 51 | + if (isEnabled) { |
| 52 | + res.send("Hello World!"); |
| 53 | + } else { |
| 54 | + res.send("Not enabled yet!"); |
| 55 | + } |
| 56 | +}); |
| 57 | + |
| 58 | +/** |
| 59 | + * Start the server |
| 60 | + */ |
| 61 | +app.listen(PORT, () => { |
| 62 | + console.log(`Server running at http://localhost:${PORT}`); |
| 63 | +}); |
0 commit comments