Skip to content
Snippets Groups Projects
Commit 0be41968 authored by ALGLAVE Ivan's avatar ALGLAVE Ivan
Browse files

Added interceptor with logging

parent ab81cd0c
No related branches found
No related tags found
1 merge request!2Crud groups
......@@ -6,14 +6,17 @@ import {
Delete,
Param,
Body,
UseInterceptors,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { HttpInterceptor } from '../interceptors/http.interceptor';
import { CreateGroupDto } from './dto/create-group.dto';
import { UpdateGroupDto } from './dto/update-group.dto';
import { GroupEntity } from './entities/group.entity';
import { GroupsService } from './groups.service';
@Controller('groups')
@UseInterceptors(HttpInterceptor)
export class GroupsController {
constructor(private readonly _groupsService: GroupsService) {}
......
import { Module } from '@nestjs/common';
import { Module, Logger } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { GroupsDao } from './dao/groups.dao';
import { GroupsController } from './groups.controller';
......@@ -10,6 +10,6 @@ import { Group, GroupSchema } from './schemas/group.schema';
MongooseModule.forFeature([{ name: Group.name, schema: GroupSchema }]),
],
controllers: [GroupsController],
providers: [GroupsService, GroupsDao],
providers: [GroupsService, GroupsDao, Logger],
})
export class GroupsModule {}
import {
CallHandler,
ExecutionContext,
Injectable,
Logger,
NestInterceptor,
} from '@nestjs/common';
import { merge, Observable, of } from 'rxjs';
import { filter, map, mergeMap, tap } from 'rxjs/operators';
import { FastifyReply } from 'fastify';
@Injectable()
export class HttpInterceptor implements NestInterceptor {
/**
* Class constructor
* @param _logger
*/
constructor(private readonly _logger: Logger) {}
/**
* Intercepts all HTTP requests and responses
*
* @param context
* @param next
*/
intercept = (
context: ExecutionContext,
next: CallHandler,
): Observable<any> => {
const cls = context.getClass();
const handler = context.getHandler();
const response: FastifyReply = context
.switchToHttp()
.getResponse<FastifyReply>();
const logCtx = `${cls.name}.${handler.name}`;
return next.handle().pipe(
map((_) => of(_)),
mergeMap((obs: Observable<any>) =>
merge(
obs.pipe(
filter((_) => !!_),
map((_) => _),
),
obs.pipe(
filter((_) => !_),
tap(() => response.status(204)),
map((_) => _),
),
),
),
tap({
next: (_) =>
this._logger.log(!!_ ? JSON.stringify(_) : 'NO CONTENT', logCtx),
error: (_) => this._logger.error(_.message, JSON.stringify(_), logCtx),
}),
);
};
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment