-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathquery-builder.service.ts
624 lines (593 loc) · 16.7 KB
/
query-builder.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
import { Apollo, gql } from 'apollo-angular';
import { Injectable } from '@angular/core';
import {
BehaviorSubject,
firstValueFrom,
Observable,
ReplaySubject,
} from 'rxjs';
import { GET_QUERY_META_DATA, GET_QUERY_TYPES } from './graphql/queries';
import { ApolloQueryResult } from '@apollo/client';
import get from 'lodash/get';
import { CompositeFilterDescriptor } from '@progress/kendo-data-query';
import { Connection } from '../../utils/public-api';
import {
QueryMetaDataQueryResponse,
QueryTypes,
} from '../../models/metadata.model';
/** Interface for the variables of a query */
interface QueryVariables {
first?: number;
skip?: number;
filter?: any;
sortField?: string;
sortOrder?: string;
display?: boolean;
styles?: any;
at?: Date;
}
/** Interface for a query response */
export interface QueryResponse {
[key: string]: Connection<any>;
}
/** Field interface definition */
export interface Field {
name: string;
editor:
| 'text'
| 'boolean'
| 'attribute'
| 'select'
| 'numeric'
| 'datetime'
| 'date'
| 'time';
label?: string;
automated?: boolean;
filter: any;
fields?: Field[];
options?: { value: any; text: string }[];
}
/** Stored query field interface definition */
export interface QueryField {
name: string;
kind: 'OBJECT' | 'SCALAR' | 'LIST';
label?: string;
type?: string;
ofType?: any;
}
/** Query interface definition */
interface Query {
name: string;
fields: QueryField[];
filter?: CompositeFilterDescriptor;
sort?: {
field?: string;
order?: 'asc' | 'desc';
};
style?: any;
}
/** List of fields part of the schema but not selectable */
const NON_SELECTABLE_FIELDS = ['canUpdate', 'canDelete'];
/** List of fields part of the schema but not selectable */
const SELECTABLE_ID_FIELDS = ['id', 'incrementalId', 'form', 'lastUpdateForm'];
/** List of user fields */
const USER_FIELDS = ['id', 'name', 'username'];
/** ReferenceData identifier convention */
export const REFERENCE_DATA_END = 'Ref';
/**
* Shared query builder service. The query builder service is used by the widgets, that creates the query based on their settings.
* Query builder service only performs query on the schema generated on the go from the forms / resources definitions.
*/
@Injectable({
providedIn: 'root',
})
export class QueryBuilderService {
/** Available forms / resources queries */
private availableQueries = new BehaviorSubject<any[]>([]);
/** @returns Available forms / resources queries as observable */
get availableQueries$(): Observable<any> {
return this.availableQueries.asObservable();
}
/** Available forms / resources types */
private availableTypes = new BehaviorSubject<any[]>([]);
/** @returns Available forms / resources types as observable */
get availableTypes$(): Observable<any> {
return this.availableTypes.asObservable();
}
/** Loading indicator that asserts whether available queries are done loading */
public isDoneLoading = new ReplaySubject<boolean>();
/** Loading indicator as observable */
public isDoneLoading$ = this.isDoneLoading.asObservable();
/** Reload indicator for query types */
public reloadQueryTypes = new BehaviorSubject<any>(null);
/** User fields */
private userFields = [];
/**
* Shared query builder service. The query builder service is used by the widgets, that creates the query based on their settings.
* Query builder service only performs query on the schema generated on the go from the forms / resources definitions.
*
* @param apollo Apollo client
*/
constructor(private apollo: Apollo) {
this.isDoneLoading.next(false);
this.fetchTypes();
this.reloadQueryTypes.subscribe(() => {
this.fetchTypes();
});
}
/**
* Fetches the types from the schema.
*/
private async fetchTypes() {
this.apollo
.query<QueryTypes>({
query: GET_QUERY_TYPES,
})
.subscribe({
next: ({ data }) => {
this.isDoneLoading.next(true);
this.availableTypes.next(data.__schema.types);
this.availableQueries.next(
data.__schema.queryType.fields.filter(
(x: any) =>
x.name.startsWith('all') || x.name.endsWith(REFERENCE_DATA_END)
)
);
this.userFields = data.__schema.types
.find((x: any) => x.name === 'User')
.fields.filter((x: any) => USER_FIELDS.includes(x.name));
},
error: () => {
this.isDoneLoading.next(false);
},
});
}
/**
* Gets list of fields from a type.
*
* @param type Corresponding type from availableTypes.
* @returns List of fields of this type.
*/
private extractFieldsFromType(type: any): {
name: string;
type: {
fields: any[] | null;
kind: 'SCALAR' | 'LIST' | 'OBJECT';
name: string;
ofType?: any;
};
args: any;
}[] {
const fields = type.fields
.filter(
(x: any) =>
!NON_SELECTABLE_FIELDS.includes(x.name) &&
(SELECTABLE_ID_FIELDS.includes(x.name) || x.type.name !== 'ID') &&
(x.type.kind !== 'LIST' || x.type.ofType.name !== 'ID')
)
.map((x: any) => {
if (x.type.kind === 'OBJECT') {
return Object.assign({}, x, {
type: Object.assign({}, x.type, {
fields: x.type.fields.filter(
(y: any) =>
y.type.kind === 'SCALAR' &&
!NON_SELECTABLE_FIELDS.includes(y.name) &&
(x.type.name !== 'User' || USER_FIELDS.includes(y.name))
),
}),
});
}
return x;
})
.sort((a: any, b: any) => a.name.localeCompare(b.name));
return fields;
}
/**
* Gets list of fields from a query name.
*
* @param queryName Form / Resource query name.
* @returns List of fields of this structure.
*/
public getFields(queryName: string) {
const query = this.availableQueries
.getValue()
.find((x) => x.name === queryName);
if (query) {
if (queryName.endsWith(REFERENCE_DATA_END)) {
const type = this.availableTypes
.getValue()
.find((x) => x.name === queryName);
return type ? this.extractFieldsFromType(type) : [];
} else {
const typeName = query?.type?.name.replace('Connection', '') || '';
const type = this.availableTypes
.getValue()
.find((x) => x.name === typeName);
return type ? this.extractFieldsFromType(type) : [];
}
} else {
return [];
}
}
/**
* Gets list of fields from a type.
*
* @param typeName Form / Resource type.
* @returns List of fields of this structure.
*/
public getFieldsFromType(typeName: string): any[] {
if (typeName === 'User') {
return this.userFields;
}
const type = this.availableTypes
.getValue()
.find((x) => x.name === typeName);
return type ? this.extractFieldsFromType(type) : [];
}
/**
* Builds the fields part of the GraphQL query.
*
* @param fields List of fields to query.
* @param withId Boolean to add a default ID field.
* @returns QL document to build the query.
*/
private buildFields(fields: any[], withId = true): string[] {
const defaultField: string[] = withId ? ['id\n'] : [];
return defaultField.concat(
fields.map((x) => {
switch (x.kind) {
case 'SCALAR': {
return x.name + '\n';
}
case 'LIST': {
if (x.type.endsWith(REFERENCE_DATA_END)) {
return (
`${x.name} {
${this.buildFields(x.fields, false)}
}` + '\n'
);
}
return (
`${x.name} (
sortField: ${x.sort.field ? `"${x.sort.field}"` : null},
sortOrder: "${x.sort.order}",
first: ${get(x, 'first', null)},
filter: ${this.filterToString(x.filter)}
) {
${['canUpdate\ncanDelete\n'].concat(this.buildFields(x.fields))}
}` + '\n'
);
}
case 'OBJECT': {
return (
`${x.name} {
${this.buildFields(x.fields, !x.type.endsWith(REFERENCE_DATA_END))}
}` + '\n'
);
}
default: {
return '';
}
}
})
);
}
/**
* Builds parsable GraphQL string from the filter definition.
*
* @param filter Filter definition
* @returns GraphQL parsable string for the filter.
*/
private filterToString(filter: any): string {
if (filter.filters) {
return `{ logic: "${filter.logic}", filters: [${filter.filters.map(
(x: any) => this.filterToString(x)
)}]}`;
} else {
return `{ field: "${filter.field}", operator: "${filter.operator}", value: "${filter.value}" }`;
}
}
/**
* Builds the fields part of the GraphQL meta query.
*
* @param fields List of fields to query.
* @returns QL document to build the query.
*/
private buildMetaFields(fields: any[]): any {
if (!fields) {
return '';
}
return [''].concat(
fields.map((x) => {
const kind = x.kind || x.type?.kind;
switch (kind) {
case 'SCALAR': {
return x.name + '\n';
}
case 'LIST':
case 'OBJECT': {
const subFields = get(x, 'fields', []) || get(x, 'type.fields', []);
if (subFields.length > 0) {
return (
`${x.name} {
${this.buildMetaFields(subFields)}
}` + '\n'
);
} else {
return '';
}
}
default: {
return '';
}
}
})
);
}
/**
* Builds a form / resource query from widget settings.
* TODO: we should pass directly the query definition, instead of the settings.
*
* @param settings Widget settings.
* @param settings.query Query definition.
* @param single Should take a single record
* @returns GraphQL query.
*/
public buildQuery(
settings: { query: Query; [key: string]: any },
single = false
) {
const builtQuery = settings.query;
if (
builtQuery?.name &&
builtQuery?.fields &&
builtQuery.fields.length > 0
) {
const fields = ['canUpdate\ncanDelete\n'].concat(
this.buildFields(builtQuery.fields)
);
if (single) {
return this.singleGraphQLQuery(builtQuery.name, fields);
} else {
return this.graphqlQuery(builtQuery.name, fields);
}
} else {
return null;
}
}
/**
* Builds a graphQL query to get a single record from name and fields strings.
*
* @param name name of the query.
* @param fields fields to fetch.
* @returns GraphQL query.
*/
public singleGraphQLQuery(name: string, fields: string[] | string) {
return gql<QueryResponse, QueryVariables>`
query GetSingleRecord($id: ID! $data: JSON) {
${name}(
id: $id
data: $data
) {
${fields}
}
}
`;
}
/**
* Builds a graphQL query from name and fields strings.
*
* @param name name of the query.
* @param fields fields to fetch.
* @returns GraphQL query.
*/
public graphqlQuery(name: string, fields: string[] | string) {
return gql<QueryResponse, QueryVariables>`
query GetCustomQuery($first: Int, $skip: Int, $filter: JSON, $sortField: String, $sortOrder: String, $display: Boolean, $styles: JSON, $at: Date) {
${name}(
first: $first
skip: $skip
sortField: $sortField
sortOrder: $sortOrder
filter: $filter
display: $display
styles: $styles
at: $at
) {
edges {
node {
${fields}
}
meta
}
totalCount
pageInfo {
hasNextPage
endCursor
}
}
}
`;
}
/**
* Builds a GraphQL meta query of a form / resource from widget settings.
*
* @param query Widget query.
* @returns GraphQL meta query.
*/
public buildMetaQuery(
query: Query
): Observable<ApolloQueryResult<any>> | null {
if (query && query.fields.length > 0) {
const metaFields = this.buildMetaFields(query.fields);
// check if has any valid value in metaFields
if (metaFields.every((x: string) => !x)) {
return null;
}
const metaQuery = gql`
query GetCustomMetaQuery {
_${query.name}Meta {
${metaFields}
}
}
`;
return this.apollo.query<any>({
query: metaQuery,
variables: {},
fetchPolicy: 'cache-first',
});
} else {
return null;
}
}
/**
* Get source query ( form / resource ) from query
*
* @param query custom query
* @returns apollo query to get source
*/
public getQuerySource(
query: Query
): Observable<ApolloQueryResult<any>> | null {
if (query) {
const sourceQuery = gql`
query GetSourceQuery {
_${query.name}Meta {
_source
}
}
`;
return this.apollo.query<any>({
query: sourceQuery,
variables: {},
fetchPolicy: 'cache-first',
});
} else {
return null;
}
}
/**
* Get metadata of form or resource
*
* @param id id of form or resource
* @returns metadata query
*/
public getQueryMetaData(id: string) {
return this.apollo.query<QueryMetaDataQueryResponse>({
query: GET_QUERY_META_DATA,
variables: {
id,
},
fetchPolicy: 'cache-first',
});
}
/**
* Returns the query name from a resource name.
*
* @param resourceName Resource name
* @returns Query name
*/
public getQueryNameFromResourceName(resourceName: string): any {
const nameTrimmed = resourceName
.replace(/_|-/g, '')
.replace(/\s+(?=\d)/g, '_')
.replace(/\s/g, '')
.toLowerCase();
return (
this.availableQueries
.getValue()
.find((x) => x.type.name.toLowerCase() === nameTrimmed + 'connection')
?.name || ''
);
}
/**
* Finds the source of a query.
* Used in order to find related forms.
*
* @param queryName Query name
* @returns Apollo query.
*/
public sourceQuery(queryName: string): any {
const queries = this.availableQueries.getValue().map((x) => x.name);
if (queries.includes(queryName)) {
const query = gql`
query GetCustomSourceQuery {
_${queryName}Meta {
_source
}
}
`;
return this.apollo.query<any>({
query,
variables: {},
});
} else {
return null;
}
}
/**
* Format fields for filters.
*
* @param query custom query.
* @returns filter fields as Promise
*/
public async getFilterFields(query: any): Promise<Field[]> {
if (query) {
const querySource$ = this.getQuerySource(query);
const sourceQuery = querySource$ && firstValueFrom(querySource$);
if (sourceQuery) {
const res = await sourceQuery;
for (const field in res.data) {
if (Object.prototype.hasOwnProperty.call(res.data, field)) {
const source = get(res.data[field], '_source', null);
if (source) {
const metaQuery = firstValueFrom(this.getQueryMetaData(source));
const res2 = await metaQuery;
const dataset = res2.data.form
? res2.data.form
: res2.data.resource
? res2.data.resource
: null;
if (!dataset) return [];
return get(dataset, 'metadata', [])
.filter((x: any) => x.filterable !== false)
.map((x: any) => ({ ...x }));
}
}
}
} else {
return [];
}
}
return [];
}
/**
* Get the right fields to be displayed in group
*
* @param type type to get fields from
* @param previousTypes param to avoid circular dependencies and infinite loading
* @returns field deconfined
*/
public deconfineFields(type: any, previousTypes: Set<any>): any {
return this.getFieldsFromType(type.name ?? type.ofType.name)
.filter(
(field) =>
field.type.name !== 'ID' &&
(field.type.kind === 'SCALAR' ||
field.type.kind === 'LIST' ||
field.type.kind === 'OBJECT') &&
!previousTypes.has(field.type.name ?? field.type.ofType.name) //prevents infinite loops
)
.map((field: any) => {
if (field.type.kind === 'LIST' || field.type.kind === 'OBJECT') {
field.fields = this.deconfineFields(
field.type,
previousTypes?.add(field.type.name ?? field.type.ofType.name)
);
}
return field;
});
}
}