1
1
import { parse , print } from 'graphql' ;
2
2
import { set } from 'lodash' ;
3
+ import { Repository } from 'typeorm' ;
3
4
4
5
import { AddKeyValueInObjectProps , GetInfoFromQueryProps } from './types' ;
5
6
@@ -32,10 +33,11 @@ const addKeyValuesInObject = <Entity>({
32
33
return { relations, select } ;
33
34
} ;
34
35
35
- export const getConditionFromGqlQuery = < Entity > (
36
+ export function getConditionFromGqlQuery < Entity > (
37
+ this : Repository < Entity > ,
36
38
query : string ,
37
39
hasCountType ?: boolean ,
38
- ) : GetInfoFromQueryProps < Entity > => {
40
+ ) : GetInfoFromQueryProps < Entity > {
39
41
const ast = parse ( query ) ;
40
42
const operationJson = print ( ast ) ;
41
43
@@ -52,12 +54,21 @@ export const getConditionFromGqlQuery = <Entity>(
52
54
const stack = [ ] ;
53
55
54
56
const regex = / [ \s \{ ] / g;
57
+ let lastMetadata = this . metadata ;
55
58
56
59
return splitted . reduce (
57
60
( acc , line ) => {
58
61
const replacedLine = line . replace ( regex , '' ) ;
62
+
59
63
if ( line . includes ( '{' ) ) {
60
64
stack . push ( replacedLine ) ;
65
+ const isFirstLineDataType = hasCountType && replacedLine === DATA ;
66
+
67
+ if ( ! isFirstLineDataType ) {
68
+ lastMetadata = lastMetadata . relations . find (
69
+ ( v ) => v . propertyName === replacedLine ,
70
+ ) . inverseEntityMetadata ;
71
+ }
61
72
62
73
return addKeyValuesInObject ( {
63
74
stack,
@@ -67,13 +78,33 @@ export const getConditionFromGqlQuery = <Entity>(
67
78
hasCountType,
68
79
} ) ;
69
80
} else if ( line . includes ( '}' ) ) {
81
+ const hasDataTypeInStack =
82
+ hasCountType && stack . length && stack [ 0 ] === DATA ;
83
+
84
+ lastMetadata =
85
+ stack . length < ( hasDataTypeInStack ? 3 : 2 )
86
+ ? this . metadata
87
+ : lastMetadata . relations . find (
88
+ ( v ) => v . propertyName === stack [ stack . length - 2 ] ,
89
+ ) . inverseEntityMetadata ;
90
+
70
91
stack . pop ( ) ;
71
92
72
93
return acc ;
73
94
}
74
95
96
+ const addedStack = [ ...stack , replacedLine ] ;
97
+
98
+ if (
99
+ ! [ ...lastMetadata . columns , ...lastMetadata . relations ]
100
+ . map ( ( v ) => v . propertyName )
101
+ . includes ( addedStack [ addedStack . length - 1 ] )
102
+ ) {
103
+ return acc ;
104
+ }
105
+
75
106
return addKeyValuesInObject ( {
76
- stack : [ ... stack , replacedLine ] ,
107
+ stack : addedStack ,
77
108
relations : acc . relations ,
78
109
select : acc . select ,
79
110
hasCountType,
@@ -84,4 +115,4 @@ export const getConditionFromGqlQuery = <Entity>(
84
115
select : { } ,
85
116
} ,
86
117
) ;
87
- } ;
118
+ }
0 commit comments