Skip to content

Commit

Permalink
feat: rabbitMQ
Browse files Browse the repository at this point in the history
  • Loading branch information
gregorsulcer committed Dec 15, 2023
1 parent 1b3a522 commit ad24996
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { Module } from '@nestjs/common';
import {
MiddlewareConsumer,
Module,
NestModule,
RequestMethod,
} from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as process from 'process';
Expand All @@ -9,6 +14,7 @@ import { OffersModule } from './api/offers/offers.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import configuration from './config/configuration';
import { HttpModule } from '@nestjs/axios';
import { LoggerMiddleware } from './middleware/logger.middleware';

@Module({
imports: [
Expand All @@ -32,4 +38,10 @@ import { HttpModule } from '@nestjs/axios';
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
2 changes: 2 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import { Logger as NestLogger } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import 'dotenv/config';
import * as process from 'process';
import { setupRabbitMQ } from './rabbitmq/rabbitmq';

async function bootstrap() {
const app = await NestFactory.create(AppModule, { cors: { origin: '*' } });
app.setGlobalPrefix('api/v1');
app.useGlobalPipes(new ValidationPipe());
setupRabbitMQ();

const config = new DocumentBuilder()
.setTitle('Discounts-service api')
Expand Down
47 changes: 47 additions & 0 deletions src/middleware/logger.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { v4 as uuidd } from 'uuid';
import * as process from 'process';
import { getRabbitMQChannel } from '../rabbitmq/rabbitmq';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
if (next) {
next();
}

const correlationIdHeader = 'X-Correlation-Id';
if (!req[correlationIdHeader]) {
req.headers[correlationIdHeader] = uuidd();
}

const timestamp = new Date().toISOString();
const urlString = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
const serviceName = '[discounts-service]';
const message = `<* ${req.method} ${req.originalUrl} *>`;

res.on('finish', () => {
const { statusCode } = res;

const log = {
timestamp,
type: statusCode >= 500 ? 'ERROR' : statusCode >= 400 ? 'WARN' : 'INFO',
correlationId: req.headers[correlationIdHeader],
urlString,
message,
serviceName,
};

const rabbitMQChannel = getRabbitMQChannel();
if (rabbitMQChannel) {
rabbitMQChannel.publish(
process.env.RABBITMQ_EXCHANGE,
'',
Buffer.from(JSON.stringify(log)),
);
console.log('Log message sent to RabbitMQ:', log);
}
});
}
}
29 changes: 29 additions & 0 deletions src/rabbitmq/rabbitmq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as process from 'process';
import * as amqp from 'amqplib/callback_api';

const rabbitMQURL = process.env.RABBITMQ_URL;
const rabbitMQExchange = process.env.EXCHANGE_NAME;
const rabbitMQQueue = process.env.QUEUE_NAME;
let rabbitMQChannel: amqp.Channel;

export const setupRabbitMQ = () => {
try {
amqp.connect(rabbitMQURL, (error0, connection) => {
if (error0) throw error0;

connection.createChannel((error1, channel) => {
if (error1) throw error1;

channel.assertExchange(rabbitMQExchange, 'direct', { durable: true });
channel.assertQueue(rabbitMQQueue, { durable: true });
channel.bindQueue(rabbitMQQueue, rabbitMQExchange, '');
rabbitMQChannel = channel;
console.log('Connected to RabbitMQ');
});
});
} catch (e) {
console.log(e);
}
};

export const getRabbitMQChannel = () => rabbitMQChannel;

0 comments on commit ad24996

Please sign in to comment.