|
| 1 | +// app/lib/middleware/environment.js |
| 2 | + |
| 3 | +/** |
| 4 | + * Format a link as HTML |
| 5 | + * |
| 6 | + * @param {string} url - The URL to link to |
| 7 | + * @param {string} text - The link text |
| 8 | + * @returns {string} HTML anchor tag |
| 9 | + */ |
| 10 | +const formatLink = (url, text) => { |
| 11 | + return `<a href="${url}">${text}</a>` |
| 12 | +} |
| 13 | + |
| 14 | +/** |
| 15 | + * Environment middleware |
| 16 | + * Sets res.locals.environment based on the current environment |
| 17 | + * Supports: development, production, and review (for Heroku PRs) |
| 18 | + */ |
| 19 | +const environment = (req, res, next) => { |
| 20 | + const { HEROKU_BRANCH, HEROKU_PR_NUMBER, NODE_ENV } = process.env |
| 21 | + |
| 22 | + let environment = 'development' // Default to development |
| 23 | + |
| 24 | + if (NODE_ENV === 'production') { |
| 25 | + environment = 'production' |
| 26 | + } |
| 27 | + |
| 28 | + // Review apps on Heroku override the above |
| 29 | + if (HEROKU_PR_NUMBER || HEROKU_BRANCH) { |
| 30 | + environment = 'review' |
| 31 | + } |
| 32 | + |
| 33 | + const pullRequestUrl = |
| 34 | + HEROKU_PR_NUMBER && |
| 35 | + `https://github.com/NHSDigital/manage-breast-screening-prototype/pull/${HEROKU_PR_NUMBER}` |
| 36 | + |
| 37 | + const environments = { |
| 38 | + development: { |
| 39 | + colour: 'white', |
| 40 | + name: 'Prototype', |
| 41 | + text: 'This is a prototype in development.' |
| 42 | + }, |
| 43 | + production: { |
| 44 | + colour: 'grey', |
| 45 | + name: 'Prototype', |
| 46 | + text: 'This is a prototype for research.' |
| 47 | + }, |
| 48 | + review: { |
| 49 | + colour: 'purple', |
| 50 | + name: HEROKU_PR_NUMBER ? `Prototype PR ${HEROKU_PR_NUMBER}` : 'Prototype', |
| 51 | + html: HEROKU_PR_NUMBER |
| 52 | + ? `This is a prototype for review. ${formatLink(pullRequestUrl, 'View pull request')}` |
| 53 | + : 'This is a prototype for review.' |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + res.locals.environment = environments[environment] |
| 58 | + |
| 59 | + next() |
| 60 | +} |
| 61 | + |
| 62 | +module.exports = environment |
0 commit comments