Skip to content

Commit db79b18

Browse files
committed
feat:table 정보 가져오기 api user connection으로 리팩토링
1 parent fa1ea30 commit db79b18

File tree

13 files changed

+165
-207
lines changed

13 files changed

+165
-207
lines changed

BE/src/config/query-database/admin-db-manager.service.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@ export class AdminDBManager implements OnModuleInit {
1313
constructor(private readonly configService: ConfigService) {}
1414

1515
async onModuleInit() {
16-
// 서버 테스트를 위한 주석처리
17-
//this.createAdminConnection();
16+
this.createAdminConnection();
1817
}
1918

2019
private createAdminConnection() {

BE/src/config/query-database/user-db-manager.service.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
import { Injectable } from '@nestjs/common';
2-
import { QueryResult } from 'mysql2/promise';
3-
import { ConfigService } from '@nestjs/config';
2+
import { Connection, QueryResult } from 'mysql2/promise';
43

54
@Injectable()
65
export class UserDBManager {
7-
constructor(private readonly configService: ConfigService) {}
8-
async run(req: any, query: string): Promise<QueryResult> {
9-
const connection = await req.dbConnection;
6+
async run(connection: Connection, query: string): Promise<QueryResult> {
107
const [result] = await connection.query(query);
118
return result;
129
}

BE/src/query/query.controller.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,15 @@ export class QueryController {
3030
@Post('/:shellId/execute')
3131
@UseGuards(ShellGuard)
3232
async executeQuery(
33-
@Req() req: Request,
33+
@Req() req: any,
3434
@Param('shellId') shellId: number,
3535
@Body() queryDto: QueryDto,
3636
) {
37-
return await this.queryService.execute(req, shellId, queryDto);
37+
return await this.queryService.execute(
38+
req.dbConnection,
39+
req.sessionID,
40+
shellId,
41+
queryDto,
42+
);
3843
}
3944
}

BE/src/query/query.service.ts

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
22
import { QueryDto } from './dto/query.dto';
33
import { QueryType } from '../common/enums/query-type.enum';
44
import { ShellService } from '../shell/shell.service';
5-
import { ResultSetHeader, RowDataPacket } from 'mysql2/promise';
5+
import { Connection, ResultSetHeader, RowDataPacket } from 'mysql2/promise';
66
import { Shell } from '../shell/shell.entity';
77
import { UserDBManager } from '../config/query-database/user-db-manager.service';
88
import { UsageService } from 'src/usage/usage.service';
@@ -17,12 +17,17 @@ export class QueryService {
1717
private readonly redisService: RedisService,
1818
) {}
1919

20-
async execute(req: any, shellId: number, queryDto: QueryDto) {
21-
this.redisService.setActiveUser(req.sessionID);
20+
async execute(
21+
connection: Connection,
22+
sessionId: string,
23+
shellId: number,
24+
queryDto: QueryDto,
25+
) {
26+
this.redisService.setActiveUser(sessionId);
2227
await this.shellService.findShellOrThrow(shellId);
2328

2429
const baseUpdateData = {
25-
sessionId: req.sessionID,
30+
sessionId: sessionId,
2631
query: queryDto.query,
2732
queryType: this.detectQueryType(queryDto.query),
2833
};
@@ -35,7 +40,11 @@ export class QueryService {
3540
text: '지원하지 않는 쿼리입니다.',
3641
});
3742
}
38-
updateData = await this.processQuery(req, baseUpdateData, queryDto.query);
43+
updateData = await this.processQuery(
44+
connection,
45+
baseUpdateData,
46+
queryDto.query,
47+
);
3948
} catch (e) {
4049
const text = `ERROR ${e.errno || ''} (${e.sqlState || ''}): ${e.sqlMessage || ''}`;
4150

@@ -47,21 +56,19 @@ export class QueryService {
4756
};
4857
return await this.shellService.replace(shellId, updateData);
4958
}
50-
await this.usageService.updateRowCount(req);
59+
await this.usageService.updateRowCount(sessionId);
5160
return await this.shellService.replace(shellId, updateData);
5261
}
5362

5463
private async processQuery(
55-
req: any,
64+
connection: Connection,
5665
baseUpdateData: any,
5766
query: string,
5867
): Promise<Partial<Shell>> {
5968
const isResultTable = this.existResultTable(baseUpdateData.queryType);
6069

61-
const rows = await this.userDBManager.run(req, query);
62-
const runTime = await this.measureQueryRunTime(req);
63-
64-
// Update usage
70+
const rows = await this.userDBManager.run(connection, query);
71+
const runTime = await this.measureQueryRunTime(connection);
6572

6673
let text: string;
6774
let resultTable: RowDataPacket[];
@@ -100,11 +107,12 @@ export class QueryService {
100107
return validTypes.includes(type);
101108
}
102109

103-
async measureQueryRunTime(req: any): Promise<string> {
110+
async measureQueryRunTime(connection: Connection): Promise<string> {
104111
try {
112+
const query = `SHOW PROFILES`;
105113
const rows = (await this.userDBManager.run(
106-
req,
107-
'show profiles;',
114+
connection,
115+
query,
108116
)) as RowDataPacket[];
109117
let lastQueryRunTime = rows[rows.length - 1]?.Duration;
110118
lastQueryRunTime = Math.round(lastQueryRunTime * 1000) / 1000 || 0;

BE/src/record/record.controller.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ import { ResRecordDto } from './dto/res-record.dto';
77
import { ExecuteRecordSwagger } from '../config/swagger/record-swagger.decorator';
88
import { Serialize } from '../interceptors/serialize.interceptor';
99
import { UserDBConnectionInterceptor } from '../interceptors/user-db-connection.interceptor';
10-
import { Request } from 'express';
1110

11+
@UseInterceptors(UserDBConnectionInterceptor)
1212
@ApiExtraModels(ResponseDto, ResRecordDto)
1313
@ApiTags('랜덤 데이터 생성 API')
1414
@Controller('api/record')
@@ -20,10 +20,13 @@ export class RecordController {
2020
@Serialize(ResRecordDto)
2121
@Post()
2222
async insertRandomRecord(
23-
@Req() req: Request,
23+
@Req() req: any,
2424
@Body() randomRecordInsertDto: CreateRandomRecordDto,
2525
) {
26-
await this.recordService.validateDto(randomRecordInsertDto, req.sessionID);
26+
await this.recordService.validateDto(
27+
randomRecordInsertDto,
28+
req.dbConnection,
29+
);
2730
return this.recordService.insertRandomRecord(req, randomRecordInsertDto);
2831
}
2932
}

BE/src/record/record.service.ts

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { UsageService } from '../usage/usage.service';
1616
import { FileService } from './file.service';
1717
import { TableService } from '../table/table.service';
1818
import { ResTableDto } from '../table/dto/res-table.dto';
19+
import { Connection } from "mysql2/promise";
1920

2021
@Injectable()
2122
export class RecordService {
@@ -27,38 +28,37 @@ export class RecordService {
2728

2829
async validateDto(
2930
createRandomRecordDto: CreateRandomRecordDto,
30-
identify: string,
31+
connection: Connection,
3132
) {
32-
const tableInfo: ResTableDto = (await this.tableService.find(
33-
identify,
34-
createRandomRecordDto.tableName,
35-
)) as ResTableDto;
36-
37-
if (!tableInfo?.tableName)
38-
throw new BadRequestException(
39-
`${createRandomRecordDto.tableName} 테이블이 존재하지 않습니다.`,
40-
);
41-
42-
const baseColumns = tableInfo.columns;
43-
const columnInfos: RandomColumnInfo[] = createRandomRecordDto.columns;
44-
45-
columnInfos.forEach((columnInfo) => {
46-
const targetName = columnInfo.name;
47-
const targetDomain = columnInfo.type;
48-
const baseColumn = baseColumns.find(
49-
(column) => column.name === columnInfo.name,
50-
);
51-
52-
if (!baseColumn)
53-
throw new BadRequestException(
54-
`${targetName} 컬럼이 ${createRandomRecordDto.tableName} 에 존재하지 않습니다.`,
55-
);
56-
57-
if (!this.checkDomainAvailability(baseColumn.type, targetDomain))
58-
throw new BadRequestException(
59-
`${targetName}(${baseColumn.type}) 컬럼에 ${targetDomain} 랜덤 값을 넣을 수 없습니다.`,
60-
);
61-
});
33+
// const tableInfo: ResTableDto = (await this.tableService.find(connection
34+
// createRandomRecordDto.tableName,
35+
// ))
36+
//
37+
// if (!tableInfo?.tableName)
38+
// throw new BadRequestException(
39+
// `${createRandomRecordDto.tableName} 테이블이 존재하지 않습니다.`,
40+
// );
41+
//
42+
// const baseColumns = tableInfo.columns;
43+
// const columnInfos: RandomColumnInfo[] = createRandomRecordDto.columns;
44+
//
45+
// columnInfos.forEach((columnInfo) => {
46+
// const targetName = columnInfo.name;
47+
// const targetDomain = columnInfo.type;
48+
// const baseColumn = baseColumns.find(
49+
// (column) => column.name === columnInfo.name,
50+
// );
51+
//
52+
// if (!baseColumn)
53+
// throw new BadRequestException(
54+
// `${targetName} 컬럼이 ${createRandomRecordDto.tableName} 에 존재하지 않습니다.`,
55+
// );
56+
//
57+
// if (!this.checkDomainAvailability(baseColumn.type, targetDomain))
58+
// throw new BadRequestException(
59+
// `${targetName}(${baseColumn.type}) 컬럼에 ${targetDomain} 랜덤 값을 넣을 수 없습니다.`,
60+
// );
61+
// });
6262
}
6363

6464
checkDomainAvailability(mysqlType: string, targetDomain: string) {

BE/src/table/dto/res-table.dto.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ export class ResTableDto {
77
@Expose()
88
columns: ColumnDto[];
99

10-
constructor(init?: Partial<ResTableDto>) {
11-
Object.assign(this, init);
10+
constructor(tableName: string, columns: ColumnDto[]) {
11+
this.tableName = tableName;
12+
this.columns = columns;
1213
}
1314
}
1415

@@ -25,9 +26,6 @@ export class ColumnDto {
2526
@Expose()
2627
FK: string;
2728

28-
@Expose()
29-
IDX: boolean;
30-
3129
@Expose()
3230
UQ: boolean;
3331

BE/src/table/table.controller.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
1-
import { Controller, Get, Param, Req } from '@nestjs/common';
1+
import { Controller, Get, Param, Req, UseInterceptors } from '@nestjs/common';
22
import { ApiExtraModels, ApiTags } from '@nestjs/swagger';
3-
import { Request } from 'express';
43
import { TableService } from './table.service';
54
import { Serialize } from '../interceptors/serialize.interceptor';
65
import { ResTableDto } from './dto/res-table.dto';
76
import { ResTablesDto } from './dto/res-tables.dto';
8-
import { GetTableListSwagger, GetTableSwagger } from '../config/swagger/table-swagger.decorator';
7+
import {
8+
GetTableListSwagger,
9+
GetTableSwagger,
10+
} from '../config/swagger/table-swagger.decorator';
911
import { ResponseDto } from '../common/response/response.dto';
12+
import { UserDBConnectionInterceptor } from '../interceptors/user-db-connection.interceptor';
1013

14+
@UseInterceptors(UserDBConnectionInterceptor)
1115
@ApiExtraModels(ResponseDto, ResTablesDto, ResTableDto)
1216
@ApiTags('테이블 가져오기 API')
1317
@Controller('api')
@@ -17,14 +21,14 @@ export class TableController {
1721
@GetTableListSwagger()
1822
@Serialize(ResTablesDto)
1923
@Get('/tables')
20-
async findAll(@Req() req: Request) {
21-
return await this.tableService.findAll(req.sessionID);
24+
async findAll(@Req() req: any) {
25+
return await this.tableService.findAll(req.dbConnection, req.sessionID);
2226
}
2327

2428
@GetTableSwagger()
2529
@Serialize(ResTableDto)
2630
@Get('/tables/:tableName')
27-
async find(@Req() req: Request, @Param('tableName') tableName: string) {
28-
return await this.tableService.find(req.sessionID, tableName);
31+
async find(@Req() req: any, @Param('tableName') tableName: string) {
32+
return await this.tableService.find(req.dbConnection, tableName);
2933
}
3034
}

0 commit comments

Comments
 (0)