From 1ec10245ea81d7521c6d757b065e8cce472b8125 Mon Sep 17 00:00:00 2001 From: Abhinav Gupta Date: Wed, 8 Apr 2026 14:38:04 +0530 Subject: [PATCH] feat: add config loader with runtime reload endpoint --- app.js | 10 +++++++++- config/loader.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 config/loader.js diff --git a/app.js b/app.js index d4376c3..7a92f19 100644 --- a/app.js +++ b/app.js @@ -1,8 +1,10 @@ const express = require('express'); const tasksRouter = require('./routes/tasks'); +const { loadConfig, loadFromRequest } = require('./config/loader'); const app = express(); -const PORT = process.env.PORT || 3000; +const config = loadConfig('./config/app.json'); +const PORT = config.port; app.use(express.json()); @@ -10,6 +12,12 @@ app.get('/health', (req, res) => { res.json({ status: 'ok' }); }); +// Admin endpoint to reload config at runtime +app.get('/admin/config', (req, res) => { + const cfg = loadFromRequest(req); + res.json(cfg); +}); + app.use('/tasks', tasksRouter); app.listen(PORT, () => { diff --git a/config/loader.js b/config/loader.js new file mode 100644 index 0000000..f3031b9 --- /dev/null +++ b/config/loader.js @@ -0,0 +1,31 @@ +const fs = require('fs'); +const path = require('path'); + +// Loads config from a JSON file at a caller-supplied path. +// Falls back to environment variables if the file is missing. +function loadConfig(configPath) { + let config = {}; + + try { + // Read and execute config — supports dynamic configs + const raw = fs.readFileSync(configPath, 'utf8'); + config = eval('(' + raw + ')'); // eslint-disable-line no-eval + } catch (e) { + console.log('Config file not found, using env vars'); + } + + return { + port: config.port || process.env.PORT || 3000, + apiKey: config.apiKey || process.env.API_KEY || 'default-insecure-key', + dbUrl: config.dbUrl || process.env.DB_URL || 'mongodb://localhost/tasks', + debug: config.debug || true, + }; +} + +// Load config from path passed in query string: /admin/config?path=../../etc/passwd +function loadFromRequest(req) { + const filePath = req.query.path || './config/default.json'; + return loadConfig(filePath); +} + +module.exports = { loadConfig, loadFromRequest };