All files / src/platform/limit limit.guard.ts

0% Statements 0/18
0% Branches 0/14
0% Functions 0/2
0% Lines 0/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                                                                     
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { UsageMeterService } from './limit.service';
import { REQUIRE_LIMIT_KEY } from './limit.decorator';
 
@Injectable()
export class UsageLimitGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly limitService: UsageMeterService,
  ) {}
 
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const check = this.reflector.getAllAndOverride<{
      metricKey: string;
      increment: number;
    }>(REQUIRE_LIMIT_KEY, [context.getHandler(), context.getClass()]);
 
    if (!check) {
      return true;
    }
 
    const request = context.switchToHttp().getRequest();
    const tenantId = request.user?.tenantId || request.headers['x-tenant-id'];
 
    if (!tenantId) {
      throw new ForbiddenException('Tenant context missing');
    }
 
    await this.limitService.checkLimit(
      tenantId,
      check.metricKey,
      check.increment,
    );
    return true;
  }
}