Skip to content

Instantly share code, notes, and snippets.

@codersidprogrammer
Created November 21, 2023 01:45
Show Gist options
  • Save codersidprogrammer/27a95940a827bdac5d1c0ce7bfe7b0b1 to your computer and use it in GitHub Desktop.
Save codersidprogrammer/27a95940a827bdac5d1c0ce7bfe7b0b1 to your computer and use it in GitHub Desktop.
Inteceptor untuk setiap request di elasticsearch. sesuaikan alamat host ELASTIC dan PORT nya
import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { AppController } from './app.controller';
import { RedisConfig } from './config/redis.config';
import { ElasticsearchLoggerInterceptor } from './core/interceptor/elasticlog.interceptor';
import { ElasticService } from './core/services/elastic.service';
import { CrmModule } from './modules/crm/crm.module';
import { JobBookmarkModule } from './modules/job-bookmark/job-bookmark.module';
import { JobNonroutineModule } from './modules/job-nonroutine/job-nonroutine.module';
import { QueueModule } from './modules/queue/queue.module';
import { StopreasonModule } from './modules/stopreason/stopreason.module';
import { TeamsModule } from './modules/teams/teams.module';
import { TransactionSapModule } from './modules/transaction-sap/transaction-sap.module';
import { TransactionModule } from './modules/transaction/transaction.module';
import { UsersModule } from './modules/users/users.module';
import { ElasticlogException } from './core/exception/elasticlog.exception';
import { EventEmitterModule } from '@nestjs/event-emitter';
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: '../.env',
isGlobal: true,
}),
BullModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useClass: RedisConfig,
}),
EventEmitterModule.forRoot({
maxListeners: 200,
}),
UsersModule,
JobBookmarkModule,
TransactionSapModule,
QueueModule,
TransactionModule,
StopreasonModule,
TeamsModule,
JobNonroutineModule,
CrmModule,
],
controllers: [AppController],
providers: [
ElasticService, // tambahin ini
{
provide: APP_INTERCEPTOR, //tambahin ini
useClass: ElasticsearchLoggerInterceptor, // tambahin ini
},
{
provide: APP_FILTER,
useClass: ElasticlogException,
},
],
})
export class AppModule {}
import { Client } from '@elastic/elasticsearch';
import { Injectable } from '@nestjs/common';
// core/services/elastic.service.ts
@Injectable()
export class ElasticService {
private readonly client: Client;
constructor() {
this.client = new Client({
node: process.env.ES_HOST,
});
}
async createLogOnElatic(indexName: string, dto: any) {
await this.create(indexName, dto);
}
getInstance() {
return this.client;
}
async create(indexName: string, dto: any) {
await this.client.index({
index: indexName,
document: dto,
});
}
}
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { PATH_METADATA } from '@nestjs/common/constants';
import { Reflector } from '@nestjs/core';
import { format } from 'date-fns';
import { Request, Response } from 'express';
import { Observable, from } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ElasticService } from '../services/elastic.service';
// core/interceptor/elasticlog.interceptor.ts
@Injectable()
export class ElasticsearchLoggerInterceptor implements NestInterceptor {
constructor(
private readonly elasticsearchService: ElasticService,
private readonly reflector: Reflector,
) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
const dateIndex = format(new Date(), 'ddMMyyyy');
const request = context.switchToHttp().getRequest<Request>();
const response = context.switchToHttp().getResponse<Response>();
const logData = {
timestamp: new Date().toISOString(),
path: request.url,
controllerPath: this.reflector.get<string[]>(
PATH_METADATA,
context.getClass(),
),
params: request.params,
method: request.method,
statusCode: response.statusCode,
};
return next.handle().pipe(
tap(() =>
from(
this.elasticsearchService.createLogOnElatic(
`xops-request-${dateIndex}`, // Ganti ini
{
...logData,
durationInMs: Date.now() - now,
},
),
),
),
);
}
}
dependencies: {
...
"@elastic/elasticsearch": "^8.10.0",
"@nestjs/elasticsearch": "^10.0.1"
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment