UNPKG

@nestdevx/tenant

Version:

Tenant module for multi-tenant NestJS applications.

62 lines 3.18 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var TenantMiddleware_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.TenantMiddleware = void 0; const request_context_1 = require("../../../shared/src/hooks/request-context"); const common_1 = require("@nestjs/common"); const tenant_service_1 = require("../tenant.service"); let TenantMiddleware = TenantMiddleware_1 = class TenantMiddleware { constructor(tenantService) { this.tenantService = tenantService; this.logger = new common_1.Logger(TenantMiddleware_1.name); } async use(req, res, next) { const id = req.headers['x-tenant-id'] || null; const hostName = req.hostname || null; this.logger.log(`Tenant ID: ${id}, Hostname: ${hostName}`); try { let tenant = null; if (id) { tenant = await this.tenantService.findById(id); } else if (id === null && hostName && hostName !== 'localhost') { tenant = await this.tenantService.findByHostName(hostName); } this.logger.log(`Tenant found: ${tenant.name} for ID: ${id}`); if (!tenant.isActive) { this.logger.warn(`Tenant with ID: ${id} is inactive.`); throw new common_1.UnauthorizedException(`Tenant with ID: ${tenant.name} is inactive. Please contact support.`); } (0, request_context_1.runWithContext)({ tenantId: tenant.id, tenantHostName: tenant.host }, () => { req.tenant = { id: tenant.id, hostName: tenant.host, isActive: tenant.isActive, dbUri: tenant.dbUri || 'shared', name: tenant.name, }; return next(); }); this.logger.log(`Tenant context set for ID: ${id}`); } catch (error) { this.logger.warn(`Failed to find tenant: ${error.message} for ID: ${id} - using default host.`); (0, request_context_1.runWithContext)({ tenantId: null, tenantHostName: null }, () => next()); } } }; exports.TenantMiddleware = TenantMiddleware; exports.TenantMiddleware = TenantMiddleware = TenantMiddleware_1 = __decorate([ (0, common_1.Injectable)(), __metadata("design:paramtypes", [tenant_service_1.TenantService]) ], TenantMiddleware); //# sourceMappingURL=tenant.middleware.js.map