Skip to content

Commit

Permalink
Merge pull request #112 from gsainfoteam/siwonpada/issue29
Browse files Browse the repository at this point in the history
  • Loading branch information
siwonpada authored Nov 7, 2024
2 parents cee6756 + 9dc4b10 commit d432ec7
Show file tree
Hide file tree
Showing 37 changed files with 177 additions and 77 deletions.
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"gistory",
"gsainfoteam",
"infoteam",
"LOGGABLE",
"metatype",
"nestjs",
"noreply",
"openai",
Expand Down
4 changes: 4 additions & 0 deletions libs/logger/src/decorator/loggable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';

export const LOGGABLE = Symbol('LOGGABLE');
export const Loggable = () => SetMetadata(LOGGABLE, true);
2 changes: 2 additions & 0 deletions libs/logger/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './logger.module';
export * from './logger.service';
48 changes: 48 additions & 0 deletions libs/logger/src/logger.decorator.register.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { DiscoveryService, MetadataScanner } from '@nestjs/core';
import { LOGGABLE } from './decorator/loggable';

@Injectable()
export class LoggerDecoratorRegister implements OnModuleInit {
constructor(
private readonly discoveryService: DiscoveryService,
private readonly metadataScanner: MetadataScanner,
) {}

onModuleInit() {
return this.discoveryService
.getProviders()
.filter((wrapper) => wrapper.isDependencyTreeStatic())
.filter(({ metatype, instance }) => {
if (!instance || !metatype) {
return false;
}
return Reflect.getMetadata(LOGGABLE, metatype);
})
.forEach(({ instance }) => {
this.metadataScanner
.getAllMethodNames(instance)
.forEach((methodName) => {
const originalMethod = instance[methodName];
if (typeof originalMethod !== 'function') {
return;
}
const logger = new Logger(instance.constructor.name);
instance[methodName] = function (...args: any[]) {
logger.log(`Before ${methodName}`);
const now = Date.now();
const result = originalMethod.apply(this, args);
if (result instanceof Promise) {
return result.then((resolvedResult) => {
logger.log(`After ${methodName} +${Date.now() - now}ms`);
return resolvedResult;
});
} else {
logger.log(`After ${methodName} +${Date.now() - now}ms`);
return result;
}
};
});
});
}
}
11 changes: 11 additions & 0 deletions libs/logger/src/logger.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { LoggerService } from './logger.service';
import { DiscoveryModule } from '@nestjs/core';
import { LoggerDecoratorRegister } from './logger.decorator.register';

@Module({
imports: [DiscoveryModule],
providers: [LoggerService, LoggerDecoratorRegister],
exports: [LoggerService],
})
export class LoggerModule {}
4 changes: 4 additions & 0 deletions libs/logger/src/logger.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Injectable } from '@nestjs/common';

@Injectable()
export class LoggerService {}
9 changes: 9 additions & 0 deletions libs/logger/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"declaration": true,
"outDir": "../../dist/libs/logger"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}
9 changes: 9 additions & 0 deletions nest-cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@
"compilerOptions": {
"tsConfigPath": "libs/infoteam-idp/tsconfig.lib.json"
}
},
"logger": {
"type": "library",
"root": "libs/logger",
"entryFile": "index",
"sourceRoot": "libs/logger/src",
"compilerOptions": {
"tsConfigPath": "libs/logger/tsconfig.lib.json"
}
}
}
}
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@
"moduleNameMapper": {
"^src/(.*)$": "<rootDir>/src/$1",
"^@lib/prisma(|/.*)$": "<rootDir>/libs/prisma/src/$1",
"^@lib/infoteam-idp(|/.*)$": "<rootDir>/libs/infoteam-idp/src/$1"
"^@lib/infoteam-idp(|/.*)$": "<rootDir>/libs/infoteam-idp/src/$1",
"^@lib/logger(|/.*)$": "<rootDir>/libs/logger/src/$1"
},
"rootDir": ".",
"testRegex": ".*\\.spec\\.ts$",
Expand All @@ -107,4 +108,4 @@
"<rootDir>/libs/"
]
}
}
}
3 changes: 2 additions & 1 deletion src/ai/ai.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { AiService } from './ai.service';
import { ConfigModule } from '@nestjs/config';
import { AiController } from './ai.controller';
import { UserModule } from 'src/user/user.module';
import { LoggerModule } from '@lib/logger';

@Module({
imports: [ConfigModule, UserModule],
imports: [ConfigModule, UserModule, LoggerModule],
providers: [AiService],
exports: [AiService],
controllers: [AiController],
Expand Down
2 changes: 2 additions & 0 deletions src/ai/ai.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ import {
ChatCompletionSystemMessageParam,
ChatCompletionUserMessageParam,
} from 'openai/resources';
import { Loggable } from '@lib/logger/decorator/loggable';
import * as deepl from 'deepl-node';
import { TranslateResDto } from './dto/res/translateRes.dto';
import { TranslateDto } from './dto/req/translate.dto';

@Injectable()
@Loggable()
export class AiService {
private readonly logger = new Logger(AiService.name, {
timestamp: true,
Expand Down
10 changes: 9 additions & 1 deletion src/crawl/crawl.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,17 @@ import { UserModule } from 'src/user/user.module';
import { AiModule } from 'src/ai/ai.module';
import { FcmModule } from 'src/fcm/fcm.module';
import { PrismaModule } from '@lib/prisma';
import { LoggerModule } from '@lib/logger';

@Module({
imports: [PrismaModule, ConfigModule, UserModule, AiModule, FcmModule],
imports: [
PrismaModule,
ConfigModule,
UserModule,
AiModule,
FcmModule,
LoggerModule,
],
providers: [CrawlService, CrawlRepository],
controllers: [CrawlController],
})
Expand Down
5 changes: 2 additions & 3 deletions src/crawl/crawl.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
import { Crawl, User } from '@prisma/client';
import { GetCrawlDto } from './dto/req/getCrawl.dto';
import { PrismaService } from '@lib/prisma';
import { Loggable } from '@lib/logger/decorator/loggable';

@Injectable()
@Loggable()
export class CrawlRepository {
private readonly logger = new Logger(CrawlRepository.name);
constructor(private readonly prismaService: PrismaService) {}

async getCrawlData({ url }: GetCrawlDto): Promise<Crawl | null> {
this.logger.log('getCrawlData');
return this.prismaService.crawl
.findFirst({
where: {
Expand All @@ -37,7 +38,6 @@ export class CrawlRepository {
deadline: Date | null,
user: User,
): Promise<Crawl> {
this.logger.log('createCrawl');
return this.prismaService.crawl
.create({
data: {
Expand Down Expand Up @@ -75,7 +75,6 @@ export class CrawlRepository {
{ title, body, type }: CreateCrawlDto,
id: number,
): Promise<Crawl> {
this.logger.log('updateCrawl');
return this.prismaService.crawl
.update({
where: {
Expand Down
4 changes: 2 additions & 2 deletions src/crawl/crawl.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ import { GetCrawlDto } from './dto/req/getCrawl.dto';
import { AiService } from 'src/ai/ai.service';
import { FcmService } from 'src/fcm/fcm.service';
import { FcmTargetUser } from 'src/fcm/types/fcmTargetUser.type';
import { Loggable } from '@lib/logger/decorator/loggable';

@Injectable()
@Loggable()
export class CrawlService {
private readonly logger = new Logger(CrawlService.name);
constructor(
Expand All @@ -26,7 +28,6 @@ export class CrawlService {
) {}

async getCrawlData(dto: GetCrawlDto): Promise<Crawl> {
this.logger.log('getCrawlData');
if (dto.password !== this.configService.get<string>('CRAWL_PASSWORD')) {
this.logger.debug('Invalid password');
throw new ForbiddenException('Invalid password');
Expand All @@ -39,7 +40,6 @@ export class CrawlService {
}

async createCrawl(dto: CreateCrawlDto): Promise<void> {
this.logger.log('createCrawl');
if (dto.password !== this.configService.get<string>('CRAWL_PASSWORD')) {
this.logger.debug('Invalid password');
throw new ForbiddenException('Invalid password');
Expand Down
3 changes: 2 additions & 1 deletion src/document/document.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
import { DocumentController } from './document.controller';
import { DocumentService } from './document.service';
import { FileModule } from 'src/file/file.module';
import { LoggerModule } from '@lib/logger';

@Module({
imports: [FileModule],
imports: [FileModule, LoggerModule],
controllers: [DocumentController],
providers: [DocumentService],
exports: [DocumentService],
Expand Down
8 changes: 2 additions & 6 deletions src/document/document.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Loggable } from '@lib/logger/decorator/loggable';
import { Injectable, Logger } from '@nestjs/common';
import path from 'path';
import { FileService } from 'src/file/file.service';

@Injectable()
@Loggable()
export class DocumentService {
private readonly logger = new Logger(DocumentService.name);
constructor(private readonly fileService: FileService) {}
Expand All @@ -13,7 +15,6 @@ export class DocumentService {
* @returns string[]
*/
async uploadDocuments(files: Express.Multer.File[]): Promise<string[]> {
this.logger.log('uploadDocuments called');
return Promise.all(files.map((file) => this.uploadDocument(file)));
}

Expand All @@ -23,7 +24,6 @@ export class DocumentService {
* @returns void
*/
async validateDocuments(key: string[]): Promise<void> {
this.logger.log('validateDocuments called');
await Promise.all(key.map((k) => this.validationDocument(k)));
}

Expand All @@ -33,7 +33,6 @@ export class DocumentService {
* @returns void
*/
async deleteDocuments(key: string[]): Promise<void> {
this.logger.log('deleteDocuments called');
await Promise.all(key.map((k) => this.deleteDocument(k)));
}

Expand All @@ -43,7 +42,6 @@ export class DocumentService {
* @returns string
*/
private async uploadDocument(file: Express.Multer.File): Promise<string> {
this.logger.log('uploadDocument called');
const key = `${new Date().toISOString()}-${Math.random().toString(36).substring(2)}.${path.extname(file.originalname)}`;
return this.fileService.uploadFile(file, key);
}
Expand All @@ -54,7 +52,6 @@ export class DocumentService {
* @returns void
*/
private async validationDocument(key: string): Promise<void> {
this.logger.log('validationDocument called');
return this.fileService.validateFile(key);
}

Expand All @@ -64,7 +61,6 @@ export class DocumentService {
* @returns void
*/
private async deleteDocument(key: string): Promise<void> {
this.logger.log('deleteDocument called');
return this.fileService.deleteFile(key);
}
}
2 changes: 2 additions & 0 deletions src/fcm/fcm.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import { FcmRepository } from './fcm.repository';
import { BullModule } from '@nestjs/bull';
import { FcmConsumer } from './fcm.consumer';
import { PrismaModule } from '@lib/prisma';
import { LoggerModule } from '@lib/logger';

@Module({
imports: [
ConfigModule,
PrismaModule,
BullModule.registerQueue({ name: 'fcm' }),
LoggerModule,
],
providers: [FcmService, FcmRepository, FcmConsumer],
exports: [FcmService],
Expand Down
20 changes: 14 additions & 6 deletions src/fcm/fcm.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import {
import { Content } from './types/content.type';
import { FcmToken, Prisma } from '@prisma/client';
import { PrismaService } from '@lib/prisma';
import { Loggable } from '@lib/logger/decorator/loggable';

@Injectable()
@Loggable()
export class FcmRepository {
private readonly logger = new Logger(FcmRepository.name);
constructor(private readonly prismaService: PrismaService) {}
Expand Down Expand Up @@ -36,12 +38,18 @@ export class FcmRepository {

async createLogs(content: Content, fcmTokenIds: string[]): Promise<void> {
const jsonContent = content as unknown as Prisma.JsonObject;
await this.prismaService.log.createMany({
data: fcmTokenIds.map((fcmTokenId) => ({
fcmTokenId,
content: jsonContent,
})),
});
await this.prismaService.log
.createMany({
data: fcmTokenIds.map((fcmTokenId) => ({
fcmTokenId,
content: jsonContent,
})),
})
.catch((err) => {
this.logger.error('createLogs');
this.logger.debug(err);
throw new InternalServerErrorException('Database error');
});
return;
}

Expand Down
4 changes: 2 additions & 2 deletions src/fcm/fcm.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import { FcmRepository } from './fcm.repository';
import { FcmTargetUser } from './types/fcmTargetUser.type';
import { InjectQueue } from '@nestjs/bull';
import { Queue } from 'bull';
import { Loggable } from '@lib/logger/decorator/loggable';

@Injectable()
@Loggable()
export class FcmService {
private readonly app: App;
private readonly logger = new Logger(FcmService.name);
Expand All @@ -33,7 +35,6 @@ export class FcmService {
targetUser: FcmTargetUser,
data?: Record<string, string>,
): Promise<void> {
this.logger.log(`Adding message to queue with jobId ${jobId}`);
await this.fcmQueue.add(
{ notification, targetUser, data },
{
Expand Down Expand Up @@ -84,7 +85,6 @@ export class FcmService {
tokens: string[],
data?: Record<string, string>,
): Promise<void> {
this.logger.log(`Sending message to ${tokens.length} tokens`);
// send message to each token
const result = await getMessaging(this.app).sendEachForMulticast({
tokens,
Expand Down
3 changes: 2 additions & 1 deletion src/file/file.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Module } from '@nestjs/common';
import { FileService } from './file.service';
import { ConfigModule } from '@nestjs/config';
import { LoggerModule } from '@lib/logger';

@Module({
imports: [ConfigModule],
imports: [ConfigModule, LoggerModule],
providers: [FileService],
exports: [FileService],
})
Expand Down
Loading

0 comments on commit d432ec7

Please sign in to comment.