@nestjs/common#NestInterceptor TypeScript Examples
The following examples show how to use
@nestjs/common#NestInterceptor.
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: logging.interceptor.ts From 42_checkIn with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(private readonly logger: MyLogger) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
return next
.handle()
.pipe(
tap(() =>
this.logger.log(
context.switchToHttp().getRequest().route.path,
context.getHandler().name,
Date.now() - now + 'ms',
),
),
);
}
}
Example #2
Source File: apm.interceptor.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class ApmInterceptor implements NestInterceptor {
constructor(private readonly reflector: Reflector) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
this.addRouteToSentry(context);
return next.handle().pipe(
catchError((error) => {
Sentry.captureException(error);
throw error;
}),
);
}
addRouteToSentry(context: ExecutionContext): void {
// Sentry has issues grouping transactions by route. (as of 12/14/2020)
// ex: /courses/1 and /courses/2 end up two different transactions.
// This code groups them both to /courses/:id using nest.js
// From https://forum.sentry.io/t/can-transactions-be-grouped/11403/15
const scope = Sentry.getCurrentHub().getScope();
if (scope) {
const transaction = scope.getTransaction();
if (transaction) {
const classPath: string = this.reflector.get<string>(
Constants.PATH_METADATA,
context.getClass(),
);
const handlerPath: string = this.reflector
.get<string>(Constants.PATH_METADATA, context.getHandler())
.replace(/^\//, '');
const method = context.switchToHttp().getRequest().method;
transaction.name = `${method} /api/v1/${classPath}/${handlerPath}`;
}
}
}
}
Example #3
Source File: transform.interceptor.ts From nestjs-starter with MIT License | 6 votes |
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(ctx: ExecutionContext, next: CallHandler): Observable<Response<T>> {
return next.handle().pipe(
map((data) => ({
statusCode: ctx.switchToHttp().getResponse().statusCode,
message: data?.message || 'Success response',
data: data?.output ?? data ?? null,
})),
);
}
}
Example #4
Source File: webhook.interceptor.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class WebhookInterceptor implements NestInterceptor {
constructor(
private reflector: Reflector,
private webhookService: WebhookService,
) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const webhookName = this.reflector.get<string>('webhook', context.getHandler());
const request = context.switchToHttp().getRequest() as IncomingMessage;
if (!webhookName) {
return next.handle();
}
return next.handle()
.pipe(
map((data) => {
this.webhookService.executeWebhook(webhookName, data)
return data;
})
)
}
}
Example #5
Source File: transform.interceptor.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
const request = context.switchToHttp().getRequest() as IncomingMessage;
return next.handle().pipe(map(data => {
return cleanResponse(data, ['password', 'key', 'patreonAccessToken', 'azuraCastApiKey', 'spotifyClientSecret', 'spotifyClientId']);
}));
}
}
Example #6
Source File: audit-log.interceptor.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class AuditLogInterceptor implements NestInterceptor {
constructor(
private reflector: Reflector,
private auditLogService: AuditLogService,
) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const eventName = this.reflector.get<string>('auditLog', context.getHandler());
const request = context.switchToHttp().getRequest() as IncomingMessage & { user: any };
const body = context.switchToHttp().getRequest()?.body || null;
if (!eventName) {
return next.handle();
}
this.auditLogService.log(request.user?.uuid, eventName, body, {
method: request.method,
url: request.url,
});
return next.handle();
}
}
Example #7
Source File: NestHttpLoggingInterceptor.ts From typescript-clean-architecture with MIT License | 6 votes |
@Injectable()
export class NestHttpLoggingInterceptor implements NestInterceptor {
public intercept(context: ExecutionContext, next: CallHandler): Observable<CoreApiResponse<void>> {
const request: Request = context.switchToHttp().getRequest();
const requestStartDate: number = Date.now();
return next.handle().pipe(tap((): void => {
const requestFinishDate: number = Date.now();
const message: string =
`Method: ${request.method}; ` +
`Path: ${request.path}; ` +
`SpentTime: ${requestFinishDate - requestStartDate}ms`;
Logger.log(message, NestHttpLoggingInterceptor.name);
}));
}
}
Example #8
Source File: auth-user.interceptor.ts From bank-server with MIT License | 6 votes |
@Injectable()
export class AuthUserInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest();
const user = <UserEntity>request.user;
AuthService.setAuthUser(user);
return next.handle();
}
}
Example #9
Source File: environment.interceptor.ts From relate with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class EnvironmentInterceptor implements NestInterceptor {
constructor(@Inject(SystemProvider) private readonly systemProvider: SystemProvider) {}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
const ctx = GqlExecutionContext.create(context);
const {environmentNameOrId} = ctx.getArgs();
const environment = await this.systemProvider.getEnvironment(environmentNameOrId);
ctx.getContext().environment = environment;
return next.handle();
}
}
Example #10
Source File: logging.interceptor.ts From Phantom with MIT License | 6 votes |
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
const req = context.switchToHttp().getRequest();
const method = req.method;
const url = req.url;
return next
.handle()
.pipe(
tap(() =>
Logger.log(
`${method} ${url} ${Date.now() - now}ms`,
context.getClass().name,
),
),
);
}
}
Example #11
Source File: logging.interceptor.ts From nestjs-starter-rest-api with MIT License | 6 votes |
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(private appLogger: AppLogger) {
this.appLogger.setContext(LoggingInterceptor.name);
}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest();
const method = request.method;
const ctx = createRequestContext(request);
const now = Date.now();
return next.handle().pipe(
tap(() => {
const response = context.switchToHttp().getResponse();
const statusCode = response.statusCode;
const responseTime = Date.now() - now;
const resData = { method, statusCode, responseTime };
this.appLogger.log(ctx, 'Request completed', { resData });
}),
);
}
}
Example #12
Source File: logging.interceptor.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(private appLogger: AppLogger) {
this.appLogger.setContext(LoggingInterceptor.name)
}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest()
const method = request.method
const url = request.originalUrl
const requestID = request.headers[REQUEST_ID_TOKEN_HEADER]
this.appLogger.log({ method, requestID, url })
const now = Date.now()
return next.handle().pipe(
tap(() => {
const response = context.switchToHttp().getResponse()
const statusCode = response.statusCode
const responseTime = Date.now() - now
this.appLogger.log({ method, requestID, url, statusCode, responseTime })
})
)
}
}
Example #13
Source File: zlibjson.interceptor.ts From emutypekov with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class ZLibDeflateJSONInterceptor implements NestInterceptor {
private readonly logger = new Logger(ZLibDeflateJSONInterceptor.name);
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
this.logger.debug('=> Response is zlib compressed.');
const response: Response = context.switchToHttp().getResponse();
const request: Request = context.switchToHttp().getRequest();
console.log('Request:');
console.log(request.body);
response.setHeader('Content-Type', 'application/json');
return next.handle().pipe(
map(async (body) => {
console.log('Response:');
console.log(body);
response.end(await _deflate(IO.cleanString(JSON.stringify(body))));
}),
);
}
}
Example #14
Source File: system.interceptor.ts From emutypekov with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class SystemInterceptor implements NestInterceptor {
private readonly logger = new Logger(SystemInterceptor.name);
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const req = context.getArgByIndex(0);
this.logger.debug(
`${context.getType()}: ${req.socket.remoteAddress} => Request: ${
req.url
}`,
);
const response: Response = context.switchToHttp().getResponse();
response.setHeader('X-Powered-By', 'EmuTypekov');
response.setHeader('Set-Cookie', 'PHPSESSID=undefined');
return next.handle().pipe(
map((body) => {
return body;
}),
);
}
}
Example #15
Source File: jaeger.intercetor.d.ts From nest-jaeger with MIT License | 6 votes |
export declare class JaegerInterceptor implements NestInterceptor {
private tracer;
private span;
private tracing_tag;
private req_cb;
private res_cb;
constructor(cfg?: {}, opt?: {}, req_cb?: any, res_cb?: any);
intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
}
Example #16
Source File: file.decorator.ts From aqualink-app with MIT License | 6 votes |
@Injectable()
export class MissingConfigInterceptor implements NestInterceptor {
// eslint-disable-next-line class-methods-use-this
intercept(): Observable<any> {
throw new HttpException(
'File upload is not configured at the moment. Contact an admin for help.',
HttpStatus.NOT_IMPLEMENTED,
);
}
}
Example #17
Source File: logging.interceptor.ts From nestjs-mercurius with MIT License | 6 votes |
@Injectable({ scope: Scope.REQUEST })
export class Interceptor implements NestInterceptor {
static COUNTER = 0;
static REQUEST_SCOPED_DATA = [];
constructor(@Inject('REQUEST_ID') private requestId: number) {
Interceptor.COUNTER++;
}
intercept(context: ExecutionContext, call: CallHandler): Observable<any> {
Interceptor.REQUEST_SCOPED_DATA.push(this.requestId);
return call.handle();
}
}
Example #18
Source File: serialization.interceptor.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class SerializeInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((args) => {
const SerializeType = getSerializeType(context.getHandler());
const entity = new SerializeType();
return Object.assign(entity, args);
}),
);
}
}
Example #19
Source File: wrap-response.interceptor.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class WrapResponseInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((...args) => {
const serializeOptions: any = {};
const { data, options, collectionName } = args[0];
if (data && collectionName) {
if (data.length) {
serializeOptions.attributes = Object.keys(_.omit(data[0], ['_id', 'id']));
data.forEach((item: any) => {
// eslint-disable-next-line no-param-reassign
item.id = item._id;
// eslint-disable-next-line no-param-reassign
delete item._id;
});
} else {
serializeOptions.attributes = Object.keys(_.omit(data, ['_id', 'id']));
}
if (options) {
serializeOptions.topLevelLinks = PaginationUtils.getPaginationLinks(
options.location,
options.paginationParams,
options.totalCount,
);
serializeOptions.meta = { totalCount: options.totalCount };
}
return new Serializer(collectionName, serializeOptions).serialize(data);
}
return {
data: args[0].data ?? args[0],
};
}),
);
}
}
Example #20
Source File: aclFilterResponse.interceptor.ts From amplication with Apache License 2.0 | 6 votes |
@Injectable()
export class AclFilterResponseInterceptor implements NestInterceptor {
constructor(
@InjectRolesBuilder() private readonly rolesBuilder: RolesBuilder,
private readonly reflector: Reflector
) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const [permissionsRoles]: any = this.reflector.getAllAndMerge<string[]>(
"roles",
[context.getHandler(), context.getClass()]
);
const permission = this.rolesBuilder.permission({
role: permissionsRoles.role,
action: permissionsRoles.action,
possession: permissionsRoles.possession,
resource: permissionsRoles.resource,
});
return next.handle().pipe(
map((data) => {
if (Array.isArray(data)) {
return data.map((results: any) => permission.filter(results));
} else {
return permission.filter(data);
}
})
);
}
}
Example #21
Source File: wrap-response.interceptor.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class WrapResponseInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((...args) => {
// if this an error response then return first object if no then second..
return {
data: args[0],
};
}),
);
}
}
Example #22
Source File: wrap-response.interceptor.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class WrapResponseInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((...args) => {
return {
data: args[0].data ?? args[0],
};
}),
);
}
}
Example #23
Source File: wrap-response.interceptor.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class WrapResponseInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((...args) => {
return {
data: args[0].data ?? args[0],
};
}),
);
}
}
Example #24
Source File: serialization.interceptor.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class SerializeInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((args) => {
const SerializeType = getSerializeType(context.getHandler());
const entity = new SerializeType();
if (Array.isArray(args)) {
return Object.assign(entity, { data: args });
} else {
return Object.assign(entity, args);
}
}),
);
}
}
Example #25
Source File: log.interceptor.ts From nestjs-mercurius with MIT License | 6 votes |
export class LogInterceptor implements NestInterceptor {
private logger = new Logger(LogInterceptor.name, { timestamp: true });
intercept(
context: ExecutionContext,
next: CallHandler<any>,
): Observable<any> {
const ctx = GqlExecutionContext.create(context);
this.logger.warn(
`Before - ${ctx.getClass().name}@${ctx.getHandler().name}`,
);
return next
.handle()
.pipe(
tap(() =>
this.logger.warn(
`After - ${ctx.getClass().name}@${ctx.getHandler().name}`,
),
),
);
}
}
Example #26
Source File: gcloud-stroage-file.interceptor.ts From nestjs-gcloud-storage with MIT License | 6 votes |
export function GCloudStorageFileInterceptor(
fieldName: string,
localOptions?: MulterOptions,
gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
@Injectable()
class MixinInterceptor implements NestInterceptor {
public interceptor: NestInterceptor;
constructor(private readonly gcloudStorage: GCloudStorageService) {
this.interceptor = new (FileInterceptor(fieldName, localOptions))();
}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
(await this.interceptor.intercept(context, next)) as Observable<any>;
const request = context.switchToHttp().getRequest();
const file = request[fieldName];
if (!file) {
Logger.error(
'GCloudStorageFileInterceptor',
`Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFileInterceptor('${fieldName}')?`,
);
return;
}
const storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);
file.storageUrl = storageUrl;
return next.handle();
}
}
const Interceptor = mixin(MixinInterceptor);
return Interceptor as Type<NestInterceptor>;
}
Example #27
Source File: gcloud-stroage-file.interceptor.ts From nestjs-gcloud-storage with MIT License | 6 votes |
@Injectable()
class MixinInterceptor implements NestInterceptor {
public interceptor: NestInterceptor;
constructor(private readonly gcloudStorage: GCloudStorageService) {
this.interceptor = new (FileInterceptor(fieldName, localOptions))();
}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
(await this.interceptor.intercept(context, next)) as Observable<any>;
const request = context.switchToHttp().getRequest();
const file = request[fieldName];
if (!file) {
Logger.error(
'GCloudStorageFileInterceptor',
`Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFileInterceptor('${fieldName}')?`,
);
return;
}
const storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);
file.storageUrl = storageUrl;
return next.handle();
}
}
Example #28
Source File: gcloud-storage-files.interceptor.ts From nestjs-gcloud-storage with MIT License | 6 votes |
export function GCloudStorageFilesInterceptor(
fieldName: string,
localOptions?: MulterOptions,
gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
@Injectable()
class MixinInterceptor implements NestInterceptor {
public interceptor: NestInterceptor;
constructor(private readonly gcloudStorage: GCloudStorageService) {
this.interceptor = new (FilesInterceptor(fieldName, 20, localOptions))();
}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
(await this.interceptor.intercept(context, next)) as Observable<any>;
const request = context.switchToHttp().getRequest();
const files = request[fieldName];
if (!files.length) {
Logger.error(
'GCloudStorageFilesInterceptor',
`Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFilesInterceptor('${fieldName}')?`,
);
return;
}
for (const file of files) file.storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);
return next.handle();
}
}
const Interceptor = mixin(MixinInterceptor);
return Interceptor as Type<NestInterceptor>;
}
Example #29
Source File: wrap-response.interceptor.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class WrapResponseInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((...args) => {
const serializeOptions: any = {};
const { data, options, collectionName } = args[0];
if (data && collectionName) {
if (data.length) {
serializeOptions.attributes = Object.keys(_.omit(data[0], ['_id', 'id']));
data.forEach((item: any) => {
// eslint-disable-next-line no-param-reassign
item.id = item._id;
// eslint-disable-next-line no-param-reassign
delete item._id;
});
} else {
serializeOptions.attributes = Object.keys(_.omit(data, ['_id', 'id']));
}
if (options) {
serializeOptions.topLevelLinks = PaginationUtils.getPaginationLinks(
options.location,
options.paginationParams,
options.totalCount,
);
serializeOptions.meta = { totalCount: options.totalCount };
}
return new Serializer(collectionName, serializeOptions).serialize(data);
}
return {
data: args[0].data ?? args[0],
};
}),
);
}
}