@nestjs/core#Reflector TypeScript Examples
The following examples show how to use
@nestjs/core#Reflector.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: access.guard.spec.ts From nest-casl with MIT License | 7 votes |
describe('AccessGuard', () => {
const req = new Object();
let abilityMetadata: unknown = {};
let accessGuard: AccessGuard;
let accessService: AccessService;
beforeEach(async () => {
CaslConfig.getRootOptions = jest.fn().mockImplementation(() => ({}));
const moduleRef = await Test.createTestingModule({
providers: [
AccessGuard,
{ provide: Reflector, useValue: { get: jest.fn().mockImplementation(() => abilityMetadata) } },
{ provide: AccessService, useValue: { canActivateAbility: jest.fn() } },
],
}).compile();
accessService = moduleRef.get<AccessService>(AccessService);
accessGuard = moduleRef.get<AccessGuard>(AccessGuard);
});
it('passes context request and ability to AccessService.canActivateAbility method', async () => {
const context = new ExecutionContextHost([req, undefined, { req }]);
await accessGuard.canActivate(context);
expect(accessService.canActivateAbility).toBeCalledWith(req, abilityMetadata);
});
it('passes context request and ability to AccessService.canActivateAbility method', async () => {
abilityMetadata = undefined;
const context = new ExecutionContextHost([req, undefined, { req }]);
await accessGuard.canActivate(context);
expect(accessService.canActivateAbility).toBeCalledWith(req, abilityMetadata);
});
});
Example #2
Source File: auth.guard.ts From nest-keycloak-connect with MIT License | 6 votes |
constructor(
@Inject(KEYCLOAK_INSTANCE)
private singleTenant: KeycloakConnect.Keycloak,
@Inject(KEYCLOAK_CONNECT_OPTIONS)
private keycloakOpts: KeycloakConnectConfig,
@Inject(KEYCLOAK_LOGGER)
private logger: Logger,
private multiTenant: KeycloakMultiTenantService,
private readonly reflector: Reflector,
) {}
Example #3
Source File: set-recaptcha-options.spec.ts From google-recaptcha with MIT License | 6 votes |
describe('Set recaptcha options decorator', () => {
let controller: TestController;
let reflector: Reflector;
beforeAll(async () => {
controller = new TestController();
reflector = new Reflector();
});
test('Test options', () => {
const executionContext = createExecutionContext(controller.submitWithSetRecaptchaOptionsDecorator, {});
const handler = executionContext.getHandler();
const options: VerifyResponseDecoratorOptions = reflector.get(RECAPTCHA_VALIDATION_OPTIONS, handler);
expect(options.response).toBeUndefined();
expect(options.action).toBe('TestOptions');
expect(options.score).toBe(0.5);
});
});
Example #4
Source File: resource.guard.ts From nest-keycloak-connect with MIT License | 6 votes |
constructor(
@Inject(KEYCLOAK_INSTANCE)
private singleTenant: KeycloakConnect.Keycloak,
@Inject(KEYCLOAK_CONNECT_OPTIONS)
private keycloakOpts: KeycloakConnectConfig,
@Inject(KEYCLOAK_LOGGER)
private logger: Logger,
private multiTenant: KeycloakMultiTenantService,
private readonly reflector: Reflector,
) {}
Example #5
Source File: google-recaptcha.module.ts From google-recaptcha with MIT License | 6 votes |
static forRoot(options: GoogleRecaptchaModuleOptions): DynamicModule {
const providers: Provider[] = [
GoogleRecaptchaGuard,
GoogleRecaptchaValidator,
RecaptchaRequestResolver,
{
provide: RECAPTCHA_OPTIONS,
useValue: options,
},
];
const httpModule = this.resolveHttpModule();
const internalProviders: Provider[] = [
Reflector,
{
provide: RECAPTCHA_HTTP_SERVICE,
useFactory: (axiosInstance: axios.AxiosInstance) => new httpModule.HttpService(axiosInstance),
inject: [
RECAPTCHA_AXIOS_INSTANCE,
],
},
{
provide: RECAPTCHA_AXIOS_INSTANCE,
useFactory: () => axios.default.create(this.transformAxiosConfig(options.axiosConfig)),
},
];
return {
global: true,
module: GoogleRecaptchaModule,
imports: [
httpModule.HttpModule,
],
providers: providers.concat(internalProviders),
exports: providers,
}
}
Example #6
Source File: main.ts From bank-server with MIT License | 6 votes |
async function bootstrap(): Promise<void> {
initializeTransactionalContext();
patchTypeORMRepositoryWithBaseRepository();
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
new ExpressAdapter(),
{ cors: true },
);
app.enable('trust proxy');
app.use(helmet());
app.use(RateLimit({ windowMs: 15 * 60 * 1000, max: 200 }));
app.use(compression());
app.use(morgan('combined'));
app.setGlobalPrefix('bank');
const reflector = app.get(Reflector);
app.useGlobalInterceptors(new ClassSerializerInterceptor(reflector));
app.useGlobalFilters(
new HttpExceptionFilter(reflector),
new QueryFailedFilter(reflector),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
dismissDefaultMessages: true,
validationError: { target: false },
}),
);
setupSwagger(app);
const configService = app.get(ConfigService);
await app.listen(configService.get('PORT'));
}
Example #7
Source File: mqtt.explorer.ts From nest-mqtt with MIT License | 5 votes |
private readonly reflector = new Reflector();
Example #8
Source File: tracing.interceptor.ts From nestjs-jaeger-tracing with MIT License | 5 votes |
constructor(
@InjectTracer()
private readonly tracer: Tracer,
@InjectTracerProvider()
private readonly tracerProvider: TracerProvider,
private readonly asyncContext: AsyncContext,
private readonly reflector: Reflector,
) {}
Example #9
Source File: bull-metadata.accessor.ts From nestjs-bullmq with MIT License | 5 votes |
constructor(private readonly reflector: Reflector) {}
Example #10
Source File: access.guard.ts From nest-casl with MIT License | 5 votes |
constructor(
private reflector: Reflector,
private readonly accessService: AccessService,
private moduleRef: ModuleRef,
) {}
Example #11
Source File: roles.guard.spec.ts From nestjs-rest-sample with GNU General Public License v3.0 | 5 votes |
describe('RolesGuard', () => {
let guard: RolesGuard;
let reflector: Reflector;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
RolesGuard,
{
provide: Reflector,
useValue: {
constructor: jest.fn(),
get: jest.fn(),
},
},
],
}).compile();
guard = module.get<RolesGuard>(RolesGuard);
reflector = module.get<Reflector>(Reflector);
});
afterEach(async () => {
jest.clearAllMocks();
});
it('should be defined', () => {
expect(guard).toBeDefined();
});
it('should skip(return true) if the `HasRoles` decorator is not set', async () => {
jest.spyOn(reflector, 'get').mockImplementation((a: any, b: any) => []);
const context = createMock<ExecutionContext>();
const result = await guard.canActivate(context);
expect(result).toBeTruthy();
expect(reflector.get).toBeCalled();
});
it('should return true if the `HasRoles` decorator is set', async () => {
jest
.spyOn(reflector, 'get')
.mockImplementation((a: any, b: any) => [RoleType.USER]);
const context = createMock<ExecutionContext>({
getHandler: jest.fn(),
switchToHttp: jest.fn().mockReturnValue({
getRequest: jest.fn().mockReturnValue({
user: { roles: [RoleType.USER] },
} as AuthenticatedRequest),
}),
});
const result = await guard.canActivate(context);
expect(result).toBeTruthy();
expect(reflector.get).toBeCalled();
});
it('should return false if the `HasRoles` decorator is set but role is not allowed', async () => {
jest.spyOn(reflector, 'get').mockReturnValue([RoleType.ADMIN]);
const request = {
user: { roles: [RoleType.USER] },
} as AuthenticatedRequest;
const context = createMock<ExecutionContext>();
const httpArgsHost = createMock<HttpArgumentsHost>({
getRequest: () => request,
});
context.switchToHttp.mockImplementation(() => httpArgsHost);
const result = await guard.canActivate(context);
expect(result).toBeFalsy();
expect(reflector.get).toBeCalled();
});
});
Example #12
Source File: roles.guard.ts From pandaid with MIT License | 5 votes |
constructor(private reflector: Reflector) {}
Example #13
Source File: FormData.interceptor.ts From nestjs-form-data with MIT License | 5 votes |
reflector: Reflector = new Reflector();
Example #14
Source File: roles.guard.ts From nestjs-starter-rest-api with MIT License | 5 votes |
constructor(private reflector: Reflector) {}
Example #15
Source File: roles.guard.ts From api with GNU Affero General Public License v3.0 | 5 votes |
constructor(private reflector: Reflector) {}
Example #16
Source File: bad-request.filter.ts From bank-server with MIT License | 5 votes |
constructor(public reflector: Reflector) {}
Example #17
Source File: roles.guard.ts From MyAPI with MIT License | 5 votes |
constructor(
private readonly reflector: Reflector
) {}
Example #18
Source File: HttpRoleAuthGuard.ts From typescript-clean-architecture with MIT License | 5 votes |
constructor(
private readonly reflector: Reflector
) {}
Example #19
Source File: audit-log.interceptor.ts From radiopanel with GNU General Public License v3.0 | 5 votes |
constructor(
private reflector: Reflector,
private auditLogService: AuditLogService,
) {}
Example #20
Source File: apm.interceptor.ts From office-hours with GNU General Public License v3.0 | 5 votes |
constructor(private readonly reflector: Reflector) {}
Example #21
Source File: user-auth-guard.ts From nestjs-angular-starter with MIT License | 5 votes |
constructor(private authService: AuthService, private reflector: Reflector) {
super();
}
Example #22
Source File: auth.guard.ts From nestjs-keycloak-admin with MIT License | 5 votes |
constructor(
@Inject(KeycloakService)
private keycloak: KeycloakService,
@Inject(Reflector.name)
private readonly reflector: Reflector
) {}
Example #23
Source File: role.guard.ts From nestjs-api-example with MIT License | 5 votes |
constructor(private reflector: Reflector) {}
Example #24
Source File: roles.guard.ts From nest-js-boilerplate with MIT License | 5 votes |
constructor(
private reflector: Reflector,
) { }
Example #25
Source File: roles.guard.ts From nest-js-quiz-manager with MIT License | 5 votes |
constructor(private reflector: Reflector, private userService: UserService) {}
Example #26
Source File: defaultAuth.guard.template.ts From amplication with Apache License 2.0 | 5 votes |
constructor(private readonly reflector: Reflector) {
super();
}
Example #27
Source File: auth-guards.ts From Cromwell with MIT License | 5 votes |
constructor(private reflector: Reflector) { }
Example #28
Source File: resource.guard.ts From nestjs-keycloak-admin with MIT License | 5 votes |
constructor(
@Inject(KeycloakService)
private keycloak: KeycloakService,
private readonly reflector: Reflector
) {}
Example #29
Source File: collection.guard.ts From aqualink-app with MIT License | 5 votes |
constructor(
@InjectRepository(Collection)
private collectionRepository: Repository<Collection>,
private reflector: Reflector,
) {}