UNPKG

legendaryjs

Version:

LegendaryJS – The ultimate backend framework for speed, power, and simplicity.

42 lines (32 loc) 1.23 kB
// 📄 core/middleware/tenant.js const fs = require('fs'); const path = require('path'); const cachedTenants = new Map(); function tenantMiddleware(config) { return (req, res, next) => { if (!config?.multitenant?.enabled) return next(); const strategy = config.multitenant.strategy || 'header'; let tenantId; if (strategy === 'header') { tenantId = req.headers[config.multitenant.headerKey || 'x-tenant-id']; } else if (strategy === 'query') { tenantId = req.query.tenant; } else if (strategy === 'subdomain') { const host = req.hostname; tenantId = host.split('.')[0]; } if (!tenantId) return res.status(400).json({ error: 'Missing tenant ID' }); req.tenantId = tenantId; req.tenant = getTenantConfig(tenantId); next(); }; } function getTenantConfig(tenantId) { if (cachedTenants.has(tenantId)) return cachedTenants.get(tenantId); const file = path.join(process.cwd(), 'tenants', `${tenantId}.json`); if (!fs.existsSync(file)) return {}; const config = JSON.parse(fs.readFileSync(file)); cachedTenants.set(tenantId, config); return config; } module.exports = { tenantMiddleware, getTenantConfig };