UNPKG

express-multitenant-kit

Version:

A lightweight helper module for building multi-tenant Express.js applications. Includes JWT-based route protection, dynamic route handling, and integration with express-tenant-router.

33 lines (26 loc) 1.1 kB
const path = require("path"); function routeHandler({ privateGuard } = {}) { return async function (req, res, next) { const tenant = req.tenant; if (!tenant) return res.status(400).json({ error: "Tenant not attached" }); const routeRequested = req.params.routeName; const tenantRoute = tenant.routes.find(route => route.routeName === routeRequested); if (!tenantRoute) return res.status(404).json({ error: "Route not found." }); const isPrivate = tenantRoute.routeData?.access === "private"; const executeHandler = () => { const handlerPath = path.join(process.cwd(), tenantRoute.routeHandler); const handler = require(handlerPath); handler(req, res, tenantRoute.routeData); }; if (isPrivate && privateGuard) { return privateGuard(req, res, () => { if (req.tenantAuth?.tenantId !== tenant.tenantId) { return res.status(403).json({ error: "Unauthorized tenant access" }); } executeHandler(); }); } executeHandler(); }; } module.exports = routeHandler;