1
1
import { HttpException , HttpStatus , Injectable , Logger } from "@nestjs/common" ;
2
2
import { InjectRepository } from "@nestjs/typeorm" ;
3
3
import { Game } from "./entities/game.entity" ;
4
- import { DataSource , In , Repository } from "typeorm" ;
4
+ import { DataSource , FindOptionsRelations , In , Repository } from "typeorm" ;
5
5
import { GameGenre } from "./entities/game-genre.entity" ;
6
6
import { GamePlatform } from "./entities/game-platform.entity" ;
7
7
import { GameTheme } from "./entities/game-theme.entity" ;
@@ -29,6 +29,7 @@ export type TAllowedResource = keyof typeof resourceToEntityMap;
29
29
@Injectable ( )
30
30
export class GameRepositoryService {
31
31
private readonly logger = new Logger ( GameRepositoryService . name ) ;
32
+ private readonly maximumAllowedRelationsQuery = 3 ;
32
33
33
34
/**
34
35
* @param dataSource
@@ -40,10 +41,29 @@ export class GameRepositoryService {
40
41
private readonly gameRepository : Repository < Game > ,
41
42
) { }
42
43
44
+ private validateMaximumRelations (
45
+ relations : FindOptionsRelations < Game > | undefined ,
46
+ ) {
47
+ if ( ! relations ) return ;
48
+ const totalQueriedEntries = Object . entries ( relations ) . filter (
49
+ ( [ key , value ] ) => {
50
+ // E.g.: genres: true
51
+ return key != undefined && value ;
52
+ } ,
53
+ ) . length ;
54
+ if ( totalQueriedEntries > this . maximumAllowedRelationsQuery ) {
55
+ throw new HttpException (
56
+ `For performance reasons, queries with more than ${ this . maximumAllowedRelationsQuery } relations are not allowed.` ,
57
+ HttpStatus . BAD_REQUEST ,
58
+ ) ;
59
+ }
60
+ }
61
+
43
62
async findOneById (
44
63
id : number ,
45
64
dto ?: GameRepositoryFindOneDto ,
46
65
) : Promise < Game > {
66
+ this . validateMaximumRelations ( dto ?. relations ) ;
47
67
const game = await this . gameRepository . findOne ( {
48
68
where : {
49
69
id,
@@ -64,6 +84,8 @@ export class GameRepositoryService {
64
84
) {
65
85
throw new HttpException ( "Invalid query." , HttpStatus . BAD_REQUEST ) ;
66
86
}
87
+ this . validateMaximumRelations ( dto ?. relations ) ;
88
+
67
89
const games = await this . gameRepository . find ( {
68
90
where : {
69
91
id : In ( dto ?. gameIds ) ,
0 commit comments