I have created a guard in a separate module for checking feature flags as below
@Injectable()
export class FeatureFlagGuard implements CanActivate {
constructor(
private reflector: Reflector,
private featureFlagService: FeatureFlagService
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const featureKey = this.reflector.get<string>(
FEATURE_FLAG_DECORATOR_KEY,
context.getHandler()
);
if (!featureKey) {
return true;
}
return await this.featureFlagService.isFeatureEnabled(featureKey);
}
}
and here is my decorator
import { SetMetadata } from '@nestjs/common';
export const FEATURE_FLAG_DECORATOR_KEY = 'FEATURE_FLAG';
export const FeatureEnabled = (featureName: string) =>
SetMetadata(FEATURE_FLAG_DECORATOR_KEY, featureName);
Then in appModule I provided the FeatureFlagGuard as below
providers: [
{
provide: APP_GUARD,
useClass: FeatureFlagGuard
}
]
Then in my controller
@FeatureEnabled('FEATURE1')
@Get('/check-feature-flag')
checkFeatureFlag() {
return {
date: new Date().toISOString()
};
}
When I run the code I get this error, since the reflector
is injected as null into my service
[error] [ExceptionsHandler] Cannot read properties of undefined (reading 'get')
Not sure what I missed
Thanks to @jayMcDoniel to give me a clue
The issue was the FeatureFlagService
was not exported from the module. When I exported it the issue is resolved