refactor(api): replace new Logger() with DI LoggerService and split large files

- Migrate 30 files from `new Logger(ClassName.name)` to injected LoggerService
  for consistent PII masking and centralized logging config
- Split prisma-admin-query.repository.ts (313→121 lines) into admin-stats.queries.ts
  and admin-user.queries.ts
- Split admin.controller.ts (285→154 lines) into admin-moderation.controller.ts
- Split prisma-listing.repository.ts (274→111 lines) into listing-read.queries.ts
- Update 28 test files with mock LoggerService
- All 831 tests passing, zero direct new Logger() calls remaining

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-10 05:35:04 +07:00
parent 4e71036ddd
commit 34202f2527
67 changed files with 851 additions and 653 deletions

View File

@@ -32,10 +32,13 @@ describe('ListingCreatedModerationHandler', () => {
},
};
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
handler = new ListingCreatedModerationHandler(
mockAiClient,
mockCommandBus,
mockPrisma as never,
mockLogger as any,
);
});

View File

@@ -5,7 +5,8 @@ describe('TrackEventHandler', () => {
let handler: TrackEventHandler;
beforeEach(() => {
handler = new TrackEventHandler();
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
handler = new TrackEventHandler(mockLogger as any);
});
it('tracks an event and returns result', async () => {

View File

@@ -1,5 +1,5 @@
import { Logger } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { type LoggerService } from '@modules/shared';
import { TrackEventCommand } from './track-event.command';
export interface TrackEventResult {
@@ -9,11 +9,12 @@ export interface TrackEventResult {
@CommandHandler(TrackEventCommand)
export class TrackEventHandler implements ICommandHandler<TrackEventCommand> {
private readonly logger = new Logger(TrackEventHandler.name);
constructor(private readonly logger: LoggerService) {}
async execute(command: TrackEventCommand): Promise<TrackEventResult> {
this.logger.log(
`Analytics event: ${command.eventType} on ${command.entityType}:${command.entityId}`,
'TrackEventHandler',
);
return {

View File

@@ -1,7 +1,7 @@
import { Inject, Logger } from '@nestjs/common';
import { Inject } from '@nestjs/common';
import { EventsHandler, type IEventHandler, type CommandBus } from '@nestjs/cqrs';
import { ListingCreatedEvent, ModerateListingCommand } from '@modules/listings';
import { type PrismaService } from '@modules/shared';
import { type PrismaService, type LoggerService } from '@modules/shared';
import {
AI_SERVICE_CLIENT,
type IAiServiceClient,
@@ -12,12 +12,11 @@ const AI_MODERATOR_ID = 'system:ai-moderation';
@EventsHandler(ListingCreatedEvent)
export class ListingCreatedModerationHandler implements IEventHandler<ListingCreatedEvent> {
private readonly logger = new Logger(ListingCreatedModerationHandler.name);
constructor(
@Inject(AI_SERVICE_CLIENT) private readonly aiClient: IAiServiceClient,
private readonly commandBus: CommandBus,
private readonly prisma: PrismaService,
private readonly logger: LoggerService,
) {}
async handle(event: ListingCreatedEvent): Promise<void> {
@@ -26,6 +25,7 @@ export class ListingCreatedModerationHandler implements IEventHandler<ListingCre
} catch (err) {
this.logger.warn(
`AI moderation skipped for listing ${event.aggregateId}: ${(err as Error).message}`,
'ListingCreatedModerationHandler',
);
}
}
@@ -48,6 +48,7 @@ export class ListingCreatedModerationHandler implements IEventHandler<ListingCre
if (!result.is_flagged) {
this.logger.debug(
`Listing ${event.aggregateId} passed AI moderation (score: ${result.score})`,
'ListingCreatedModerationHandler',
);
return;
}
@@ -55,6 +56,7 @@ export class ListingCreatedModerationHandler implements IEventHandler<ListingCre
this.logger.log(
`Listing ${event.aggregateId} flagged by AI moderation (score: ${result.score}, ` +
`flags: ${result.flags.map((f) => f.category).join(', ')})`,
'ListingCreatedModerationHandler',
);
const flagNotes = result.flags

View File

@@ -24,10 +24,13 @@ describe('HttpAVMService', () => {
property: { findUnique: vi.fn() },
};
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
service = new HttpAVMService(
mockAiClient,
mockFallback,
mockPrisma as never,
mockLogger as any,
);
});

View File

@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { type LoggerService } from '@modules/shared';
export interface AiPredictRequest {
area: number;
@@ -51,12 +52,11 @@ export interface IAiServiceClient {
@Injectable()
export class AiServiceClient implements IAiServiceClient {
private readonly logger = new Logger(AiServiceClient.name);
private readonly baseUrl: string;
private readonly apiKey: string;
private readonly timeoutMs: number;
constructor() {
constructor(private readonly logger: LoggerService) {
this.baseUrl = process.env['AI_SERVICE_URL'] ?? 'http://localhost:8000';
this.apiKey = process.env['AI_SERVICE_API_KEY'] ?? '';
this.timeoutMs = Number(process.env['AI_SERVICE_TIMEOUT_MS']) || 5000;

View File

@@ -1,5 +1,5 @@
import { Inject, Injectable, Logger } from '@nestjs/common';
import { type PrismaService } from '@modules/shared';
import { Inject, Injectable } from '@nestjs/common';
import { type PrismaService, type LoggerService } from '@modules/shared';
import {
type IAVMService,
type AVMParams,
@@ -15,12 +15,11 @@ import { type PrismaAVMService } from './prisma-avm.service';
@Injectable()
export class HttpAVMService implements IAVMService {
private readonly logger = new Logger(HttpAVMService.name);
constructor(
@Inject(AI_SERVICE_CLIENT) private readonly aiClient: IAiServiceClient,
private readonly fallback: PrismaAVMService,
private readonly prisma: PrismaService,
private readonly logger: LoggerService,
) {}
async estimateValue(params: AVMParams): Promise<ValuationResult> {
@@ -29,6 +28,7 @@ export class HttpAVMService implements IAVMService {
} catch (err) {
this.logger.warn(
`AI AVM service unavailable, falling back to comparables-based estimation: ${(err as Error).message}`,
'HttpAVMService',
);
return this.fallback.estimateValue(params);
}

View File

@@ -1,8 +1,8 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { type CommandBus } from '@nestjs/cqrs';
import { Cron, CronExpression } from '@nestjs/schedule';
import { PropertyType } from '@prisma/client';
import { type PrismaService } from '@modules/shared';
import { type PrismaService, type LoggerService } from '@modules/shared';
import { UpdateMarketIndexCommand } from '../../application/commands/update-market-index/update-market-index.command';
interface MarketStats {
@@ -18,16 +18,15 @@ interface MarketStats {
@Injectable()
export class MarketIndexCronService {
private readonly logger = new Logger(MarketIndexCronService.name);
constructor(
private readonly prisma: PrismaService,
private readonly commandBus: CommandBus,
private readonly logger: LoggerService,
) {}
@Cron(CronExpression.EVERY_DAY_AT_2AM, { name: 'market-index-calculation' })
async calculateMarketIndices(): Promise<void> {
this.logger.log('Starting market index calculation...');
this.logger.log('Starting market index calculation...', 'MarketIndexCronService');
const period = this.getCurrentPeriod();
@@ -54,15 +53,18 @@ export class MarketIndexCronService {
} catch (err) {
this.logger.error(
`Failed to update market index for ${stat.district}/${stat.city}/${stat.propertyType}: ${(err as Error).message}`,
undefined,
'MarketIndexCronService',
);
}
}
this.logger.log(
`Market index calculation completed: ${updatedCount}/${stats.length} indices updated for period ${period}`,
'MarketIndexCronService',
);
} catch (err) {
this.logger.error(`Market index calculation failed: ${(err as Error).message}`);
this.logger.error(`Market index calculation failed: ${(err as Error).message}`, undefined, 'MarketIndexCronService');
}
}