-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathall.ts
More file actions
744 lines (707 loc) · 22.7 KB
/
all.ts
File metadata and controls
744 lines (707 loc) · 22.7 KB
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
import { GraphQLError } from 'graphql';
import { Form, Record, ReferenceData, User, Resource } from '@models';
import extendAbilityForRecords from '@security/extendAbilityForRecords';
import { decodeCursor, encodeCursor } from '@schema/types';
import getReversedFields from '../../introspection/getReversedFields';
import getFilter, {
FLAT_DEFAULT_FIELDS,
extractFilterFields,
} from './getFilter';
import getStyle from './getStyle';
import getSortAggregation from './getSortAggregation';
import mongoose from 'mongoose';
import buildReferenceDataAggregation from '@utils/aggregation/buildReferenceDataAggregation';
import { getAccessibleFields } from '@utils/form';
import buildCalculatedFieldPipeline from '@utils/aggregation/buildCalculatedFieldPipeline';
import { logger } from '@services/logger.service';
import checkPageSize from '@utils/schema/errors/checkPageSize.util';
import { flatten, get, isArray, set } from 'lodash';
import { accessibleBy } from '@casl/mongoose';
import { graphQLAuthCheck } from '@schema/shared';
/** Default number for items to get */
const DEFAULT_FIRST = 25;
// todo: improve by only keeping used fields in the $project stage
/**
* Project aggregation.
* Reduce the volume of data to fetch
*/
const projectAggregation = [
{
$project: {
id: 1,
_id: 1,
incrementalId: 1,
_form: {
_id: 1,
name: 1,
},
_lastUpdateForm: {
_id: 1,
name: 1,
},
resource: 1,
createdAt: 1,
_createdBy: {
user: {
id: 1,
_id: 1,
name: 1,
username: 1,
},
},
modifiedAt: 1,
_lastUpdatedBy: {
user: {
id: 1,
_id: 1,
name: 1,
username: 1,
},
},
data: 1,
},
},
];
/** Default aggregation common to all records to make lookups for default fields. */
const defaultRecordAggregation = [
{ $addFields: { id: { $toString: '$_id' } } },
{
$addFields: {
'_createdBy.user.id': { $toString: '$_createdBy.user._id' },
},
},
{
$addFields: {
'_lastUpdatedBy.user.id': { $toString: '$_lastUpdatedBy.user._id' },
},
},
];
/**
* Build At aggregation, filtering out items created after this date, and using version that matches date
*
* @param at Date
* @returns At aggregation
*/
const getAtAggregation = (at: Date) => {
return [
{
$match: {
createdAt: {
$lte: at,
},
},
},
{
$lookup: {
from: 'versions',
localField: 'versions',
foreignField: '_id',
pipeline: [
{
$match: {
createdAt: {
$lte: at,
},
},
},
{
$sort: {
createdAt: -1,
},
},
{
$limit: 1,
},
],
as: '__version',
},
},
{
$unwind: {
path: '$__version',
preserveNullAndEmptyArrays: true,
},
},
{
$addFields: {
data: {
$cond: {
if: { $ifNull: ['$__version', false] },
then: '$__version.data',
else: '$data',
},
},
},
},
];
};
/**
* Get queried fields from query definition
*
* @param info graphql query info
* @returns queried fields
*/
const getQueryFields = (
info: any
): {
name: string;
fields?: string[];
arguments?: any;
}[] => {
return (
info.fieldNodes[0]?.selectionSet?.selections
?.find((x) => x.name.value === 'edges')
?.selectionSet?.selections?.find((x) => x.name.value === 'node')
?.selectionSet?.selections?.reduce(
(arr, field) => [
...arr,
{
name: field.name.value,
...(field.selectionSet && {
fields: field.selectionSet.selections.map((x) => x.name.value),
arguments: field.arguments.reduce((o, x) => {
if (x.value.value) {
Object.assign(o, { [x.name.value]: x.value.value });
}
return o;
}, {}),
}),
},
],
[]
) || []
);
};
/**
* Sort in place passed records array if needed
*
* @param records Records array to be sorted
* @param sortArgs Sort arguments
*/
const sortRecords = (records: any[], sortArgs: any): void => {
if (sortArgs.sortField && sortArgs.sortOrder) {
const sortField = FLAT_DEFAULT_FIELDS.includes(sortArgs.sortField)
? sortArgs.sortField
: `data.${sortArgs.sortField}`;
records.sort((a: any, b: any) => {
if (get(a, sortField) === get(b, sortField)) return 0;
if (sortArgs.sortOrder === 'asc') {
return get(a, sortField) > get(b, sortField) ? 1 : -1;
} else {
return get(a, sortField) < get(b, sortField) ? 1 : -1;
}
});
}
};
/**
* Returns a resolver that fetches records from resources/forms
*
* @param entityName Structure name
* @param fieldsByName structure name / fields as key, value
* @param idsByName structure name / id as key, value
* @returns The resolver function
*/
export default (entityName: string, fieldsByName: any, idsByName: any) =>
async (
parent,
{
sortField,
sortOrder = 'asc',
first = DEFAULT_FIRST,
skip = 0,
afterCursor,
filter = {},
display = false,
styles = [],
at,
},
context,
info
) => {
graphQLAuthCheck(context);
// Make sure that the page size is not too important
checkPageSize(first);
try {
const user: User = context.user;
// Id of the form / resource
const id = idsByName[entityName];
// List of form / resource fields
const fields: any[] = fieldsByName[entityName];
// Pass display argument to children resolvers
if (display) {
context.display = true;
}
// === FILTERING ===
const usedFields = extractFilterFields(filter);
if (sortField) {
usedFields.push(sortField);
}
// Get list of needed resources for the aggregation
const resourcesToQuery = [
...new Set(usedFields.map((x) => x.split('.')[0])),
].filter((x) =>
fields.find((f) => f.name === x && f.type === 'resource')
);
const resourceFieldsById = resourcesToQuery.reduce((o, x) => {
const resourceId = fields.find((f) => f.name === x).resource;
const resourceName = Object.keys(idsByName).find(
(key) => idsByName[key] == resourceId
);
const resourceFields = fieldsByName[resourceName];
return {
...o,
[resourceId]: resourceFields,
};
}, {});
context = { ...context, resourceFieldsById };
let linkedRecordsAggregation = [];
for (const resource of resourcesToQuery) {
// Build linked records aggregations
linkedRecordsAggregation = linkedRecordsAggregation.concat([
{
$addFields: {
[`data.${resource}_id`]: {
$convert: {
input: `$data.${resource}`,
to: 'objectId',
onError: null,
},
},
},
},
{
$lookup: {
from: 'records',
localField: `data.${resource}_id`,
foreignField: '_id',
as: `_${resource}`,
},
},
{
$unwind: {
path: `$_${resource}`,
preserveNullAndEmptyArrays: true,
},
},
{
$addFields: {
[`_${resource}.id`]: { $toString: `$_${resource}._id` },
},
},
]);
// Build linked records filter
const resourceId = fields.find((f) => f.name === resource).resource;
const resourceName = Object.keys(idsByName).find(
(key) => idsByName[key] == resourceId
);
const resourceFields = fieldsByName[resourceName];
const usedResourceFields = usedFields
.filter((x) => x.startsWith(`${resource}.`))
.map((x) => x.split('.')[1]);
resourceFields
.filter((x) => usedResourceFields.includes(x.name))
.map((x) =>
fields.push({
...x,
...{ name: `${resource}.${x.name}` },
})
);
}
// Get list of reference data fields to query
const referenceDataFieldsToQuery = fields.filter(
(f) =>
f.referenceData?.id &&
[...new Set(usedFields.map((x) => x.split('.')[0]))].includes(f.name)
);
// Query needed reference datas
const referenceDatas: ReferenceData[] = await ReferenceData.find({
_id: referenceDataFieldsToQuery.map((f) => f.referenceData?.id),
}).populate({
path: 'apiConfiguration',
model: 'ApiConfiguration',
select: { name: 1, endpoint: 1, graphQLEndpoint: 1 },
});
// OPTIMIZATION: Does only one query to get all related question fields.
// Check if we need to fetch any other record related to resource questions
const queryFields = getQueryFields(info);
// Build aggregation for calculated fields
const calculatedFieldsAggregation: any[] = [];
// only add calculated fields that are in the query
// in order to decrease the pipeline size
const shouldAddCalculatedFieldToPipeline = (field: any) => {
// If field is requested in the query
if (queryFields.findIndex((x) => x.name === field.name) > -1)
return true;
// If sort field is a calculated field
if (sortField === field.name) return true;
const isUsedInFilter = (qFilter: any) => {
if (qFilter.field) return qFilter.field === field.name;
return qFilter.filters?.some((f) => isUsedInFilter(f)) ?? false;
};
// Check if the field is used in the filter
if (isUsedInFilter(filter)) return true;
// Check if the field is used in any styles' filters
if (styles?.some((s) => isUsedInFilter(s.filter))) return true;
// If not used in any of the above, don't add it to the pipeline
return false;
};
fields
.filter((f) => f.isCalculated && shouldAddCalculatedFieldToPipeline(f))
.forEach((f) =>
calculatedFieldsAggregation.push(
...buildCalculatedFieldPipeline(f.expression, f.name)
)
);
// Build linked records aggregations
const linkedReferenceDataAggregation = flatten(
await Promise.all(
referenceDataFieldsToQuery.map(async (field) => {
const referenceData = referenceDatas.find(
(x) => x.id === field.referenceData.id
);
return buildReferenceDataAggregation(referenceData, field, context);
})
)
);
// Filter from the query definition
const mongooseFilter = getFilter(filter, fields, context);
// Add the basic records filter
const basicFilters = {
$or: [{ resource: id }, { form: id }],
archived: { $ne: true },
};
// Additional filter from the user permissions
const form = await Form.findOne({
$or: [{ _id: id }, { resource: id, core: true }],
})
.select('_id permissions fields')
.populate({ path: 'resource', model: 'Resource' });
const ability = await extendAbilityForRecords(user, form);
set(context, 'user.ability', ability);
const permissionFilters = Record.find(
accessibleBy(ability, 'read').Record
).getFilter();
// Finally putting all filters together
const filters = {
$and: [mongooseFilter, permissionFilters],
};
// === RUN AGGREGATION TO FETCH ITEMS ===
let items: Record[] = [];
let totalCount = 0;
// If we're using skip parameter, include them into the aggregation
if (skip || skip === 0) {
const aggregation = await Record.aggregate([
{ $match: basicFilters },
...(at ? getAtAggregation(at) : []),
...linkedRecordsAggregation,
...linkedReferenceDataAggregation,
...defaultRecordAggregation,
...calculatedFieldsAggregation,
{ $match: filters },
...projectAggregation,
...(await getSortAggregation(sortField, sortOrder, fields, context)),
{
$facet: {
items: [{ $skip: skip }, { $limit: first + 1 }],
totalCount: [
{
$count: 'count',
},
],
},
},
]);
items = aggregation[0].items;
totalCount = aggregation[0]?.totalCount[0]?.count || 0;
} else {
// If we're using cursors, get pagination filters <---- DEPRECATED ??
const cursorFilters = afterCursor
? {
_id: {
$gt: decodeCursor(afterCursor),
},
}
: {};
const aggregation = await Record.aggregate([
{ $match: basicFilters },
...linkedRecordsAggregation,
...linkedReferenceDataAggregation,
...defaultRecordAggregation,
...(await getSortAggregation(sortField, sortOrder, fields, context)),
{ $match: { $and: [filters, cursorFilters] } },
{
$facet: {
results: [{ $limit: first + 1 }],
totalCount: [
{
$count: 'count',
},
],
},
},
]);
items = aggregation[0].items;
totalCount = aggregation[0]?.totalCount[0]?.count || 0;
}
// Deal with resource/resources questions on THIS form
const resourcesFields: any[] = fields.reduce((arr, field) => {
if (field.type === 'resource' || field.type === 'resources') {
const queryField = queryFields.find((x) => x.name === field.name);
if (queryField) {
arr.push({
...field,
fields: [
...queryField.fields,
queryField.arguments?.sortField
? queryField.arguments?.sortField
: '',
].filter((f) => f), // remove '' if in array
arguments: queryField.arguments,
});
}
}
return arr;
}, []);
// Deal with resource/resources questions on OTHER forms if any
let relatedFields = [];
if (queryFields.filter((x) => x.fields).length - resourcesFields.length) {
const entities = Object.keys(fieldsByName);
const mappedRelatedFields = [];
relatedFields = entities.reduce((arr, relatedEntityName) => {
const reversedFields = getReversedFields(
fieldsByName[relatedEntityName],
id
).reduce((entityArr, x) => {
if (!mappedRelatedFields.includes(x.relatedName)) {
const queryField = queryFields.find(
(y) => x.relatedName === y.name
);
if (queryField) {
mappedRelatedFields.push(x.relatedName);
entityArr.push({
...x,
fields: [
...queryField.fields,
x.name,
queryField.arguments?.sortField
? queryField.arguments?.sortField
: '',
].filter((f) => f), // remove '' if in array
arguments: queryField.arguments,
relatedEntityName,
});
}
}
return entityArr;
}, []);
if (reversedFields.length > 0) {
arr = arr.concat(reversedFields);
}
return arr;
}, []);
}
// If we need to do this optimization, mark each item to update
if (resourcesFields.length > 0 || relatedFields.length > 0) {
const itemsToUpdate: {
item: any;
field: any;
record?: any;
records?: any[];
}[] = [];
const relatedFilters = [];
for (const item of items as any) {
item._relatedRecords = {};
item.data = item.data || {};
for (const field of resourcesFields) {
if (field.type === 'resource') {
const record = item.data[field.name];
if (record) {
itemsToUpdate.push({ item, record, field });
}
}
if (field.type === 'resources') {
const records = item.data[field.name];
if (records && records.length > 0) {
itemsToUpdate.push({ item, records, field });
}
}
}
for (const field of relatedFields) {
itemsToUpdate.push({ item, field });
relatedFilters.push({
$or: [
{ resource: idsByName[field.entityName] },
{ form: idsByName[field.entityName] },
],
[`data.${field.name}`]: item.id,
});
}
}
// Extract unique IDs
const relatedIds = [
...new Set(
itemsToUpdate.flatMap((x) => (x.record ? x.record : x.records))
),
];
// Build projection to fetch minimum data
const projection: string[] = ['createdBy', 'form'].concat(
resourcesFields.concat(relatedFields).flatMap((x) =>
x.fields.map((fieldName: string) => {
if (FLAT_DEFAULT_FIELDS.includes(fieldName)) {
return fieldName;
}
return `data.${fieldName}`;
})
)
);
const projectionObject = projection.reduce((acc, field) => {
acc[field] = 1;
return acc;
}, {});
// get aggregated fields from resource
const resourceFieldsToCalculate = [];
// get each resource in resourceFields
const promises = resourcesFields.map(async (resource: any) => {
// filter resource by resource id
const resourceData = await Resource.findById(resource.resource);
if (resourceData) {
// get each field of resourceData
resourceData.fields.forEach((rdField: any) => {
// if have the resourceDataField in resource.fields
if (
resource.fields.includes(rdField.name) &&
rdField.expression
) {
// add it to resource fields to be calculated
resourceFieldsToCalculate.push(rdField);
}
});
}
});
await Promise.all(promises);
// get the resource calculated fields
const resourceCalculatedFields = [];
resourceFieldsToCalculate.forEach((f) => {
resourceCalculatedFields.push(
...buildCalculatedFieldPipeline(f.expression, f.name)
);
});
// Fetch records
const relatedRecords = await Record.aggregate([
{
$match: {
$or: [
{
_id: {
$in: relatedIds.map((x) => new mongoose.Types.ObjectId(x)),
},
},
...relatedFilters,
],
archived: { $ne: true },
},
},
...resourceCalculatedFields,
{
$project: projectionObject,
},
]);
// Update items
for (const item of itemsToUpdate) {
if (item.record) {
const record = relatedRecords.find((x) =>
x._id.equals(item.record)
);
if (record) {
item.item._relatedRecords[item.field.name] = record;
}
}
if (item.records) {
const records = relatedRecords.filter((x) =>
item.records.some((y) => x._id.equals(y))
);
sortRecords(records, item.field.arguments);
if (records) {
item.item._relatedRecords[item.field.name] = records;
}
}
if (item.field.entityName) {
const records = relatedRecords.filter((x) => {
const value = x.data[item.field.name];
if (!value) return false;
if (isArray(value)) {
return value.includes(item.item.id);
}
return value === item.item.id;
});
sortRecords(records, item.field.arguments);
if (records && records.length > 0) {
item.item._relatedRecords[item.field.relatedName] = records;
}
}
}
}
// Construct output object and return
const hasNextPage = items.length > first;
if (hasNextPage) {
items = items.slice(0, items.length - 1);
}
// === STYLES ===
const styleRules: { items: any[]; style: any }[] = [];
// If there is a custom style rule
if (styles?.length > 0) {
// Create the filter for each style
const recordsIds = items.map((x) => x.id || x._id);
for (const style of styles) {
const styleFilter = getFilter(style.filter, fields, context);
// Get the records corresponding to the style filter
const itemsToStyle = await Record.aggregate([
{
$match: {
_id: {
$in: recordsIds.map((x) => new mongoose.Types.ObjectId(x)),
},
},
},
...calculatedFieldsAggregation,
{
$match: styleFilter,
},
{ $addFields: { id: '$_id' } },
]);
// Add the list of record and the corresponding style
styleRules.push({ items: itemsToStyle, style: style });
}
}
// === CONSTRUCT OUTPUT + RETURN ===
const edges = items.map((r) => {
const record = getAccessibleFields(r, ability);
Object.assign(record, { id: record._id });
return {
cursor: encodeCursor(record.id.toString()),
node: display ? Object.assign(record, { display, fields }) : record,
meta: {
style: getStyle(r, styleRules),
},
};
});
return {
pageInfo: {
hasNextPage,
startCursor: edges.length > 0 ? edges[0].cursor : null,
endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : null,
},
edges,
totalCount,
_source: id,
};
} catch (err) {
logger.error(err.message, { stack: err.stack });
if (err instanceof GraphQLError) {
throw new GraphQLError(err.message);
}
throw new GraphQLError(
context.i18next.t('common.errors.internalServerError')
);
}
};