feat: added graphql kafka loging middleware

feature/logging-setup
Artem-Darius Weber 2 years ago
parent 1a05a7b455
commit 331d0a0729

@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import {MiddlewareConsumer, Module} from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import {KafkaModule} from "nestjs-kafka";
@Module({
imports: [
@ -12,4 +13,8 @@ import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
}),
],
})
export class ApiGatewayModule {}
export class ApiGatewayModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(KafkaModule).forRoutes('graphql');
}
}

@ -3,9 +3,10 @@ import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import {ApiGatewayModule} from "../api-gateway/api-gateway.module";
import {KafkaConfigModule} from "../kafka/kafka.module";
@Module({
imports: [ApiGatewayModule],
imports: [ApiGatewayModule, KafkaConfigModule],
controllers: [AppController],
providers: [AppService],
})

@ -0,0 +1,14 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { KafkaProducerService } from './kafka-producer.service';
@Injectable()
export class KafkaLoggerMiddleware implements NestMiddleware {
constructor(private readonly kafkaProducer: KafkaProducerService) {}
async use(req: Request, res: Response, next: NextFunction) {
const logMessage = `Request: ${req.method} ${req.url}`;
await this.kafkaProducer.sendLogMessage('request-logs', logMessage);
next();
}
}

@ -0,0 +1,18 @@
import { Injectable } from '@nestjs/common';
import {KafkaPayload, KafkaService} from 'nestjs-kafka';
@Injectable()
export class KafkaProducerService {
TASK_PUSH_INFO = "agw";
constructor(private readonly kafkaService: KafkaService) {}
async sendLogMessage(topic: string, message: string): Promise<void> {
const payload: KafkaPayload = {
messageId: '' + new Date().valueOf(),
body: message,
messageType: this.TASK_PUSH_INFO,
topicName: this.TASK_PUSH_INFO,
};
this.kafkaService.sendMessage('log-kafka', payload);
}
}

@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { KafkaModule } from 'nestjs-kafka';
import {KafkaProducerService} from "./kafka-producer.service";
@Module({
imports: [
KafkaModule.register({
groupId: "",
clientId: 'nestjs-app',
brokers: ['localhost:9092']
}),
],
exports: [KafkaModule],
providers: [KafkaProducerService],
})
export class KafkaConfigModule {}

@ -0,0 +1,4 @@
import { Module } from '@nestjs/common';
@Module({})
export class KafkaModule {}
Loading…
Cancel
Save