Careeroza
Real World Example
Feature Flag Guard
Apps like Swiggy and Paytm launch features to a small percentage of users first. A guard reads a @Feature() flag from the handler and checks it against a flag service; disabled features answer 404 so they stay hidden.
src/flags/feature.guard.ts
import { CanActivate, ExecutionContext, Injectable, NotFoundException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { FlagsService } from './flags.service';
export const Feature = Reflector.createDecorator<string>();
@Injectable()
export class FeatureGuard implements CanActivate {
constructor(private readonly reflector: Reflector, private readonly flags: FlagsService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const flag = this.reflector.get(Feature, context.getHandler());
if (!flag) return true;
const { user } = context.switchToHttp().getRequest();
if (!(await this.flags.isEnabled(flag, user?.id))) throw new NotFoundException();
return true;
}
}
// orders.controller.ts
// @Post(':id/split-payment')
// @Feature('split-payment')
// splitPayment(...) {}