-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathdata_form.ts
More file actions
2803 lines (2664 loc) · 92.5 KB
/
data_form.ts
File metadata and controls
2803 lines (2664 loc) · 92.5 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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Document, FilterQuery, Mongoose, Types, Schema } from "mongoose";
import { Express } from "express";
import { fngServer } from "./index";
import Resource = fngServer.Resource;
import ResourceOptions = fngServer.ResourceOptions;
import ListField = fngServer.ListField;
import FngOptions = fngServer.FngOptions;
import IFngPlugin = fngServer.IFngPlugin;
import IInternalSearchResult = fngServer.IInternalSearchResult;
import ISearchResultFormatter = fngServer.ISearchResultFormatter;
import Path = fngServer.Path;
import ForeignKeyList = fngServer.ForeignKeyList;
// This part of forms-angular borrows from https://github.com/Alexandre-Strzelewicz/angular-bridge
// (now https://github.com/Unitech/angular-bridge
import _ from "lodash";
import util from "util";
import extend from "node.extend";
import async from "async";
let debug = false;
type IHiddenFields = { [fieldName: string]: boolean };
function logTheAPICalls(req: Express.Request, res: Express.Response, next) {
void res;
console.log(
"API : " +
req.method +
" " +
req.url +
" [ " +
JSON.stringify(req.body) +
" ]"
);
next();
}
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/",
"`": "`",
"=": "=",
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s) {
return entityMap[s];
});
}
function processArgs(options: any, array: Array<any>): Array<any> {
if (options.authentication) {
let authArray = _.isArray(options.authentication)
? options.authentication
: [options.authentication];
for (let i = authArray.length - 1; i >= 0; i--) {
array.splice(1, 0, authArray[i]);
}
}
if (debug) {
array.splice(1, 0, logTheAPICalls);
}
array[0] = options.urlPrefix + array[0];
return array;
}
export class FormsAngular {
app: Express;
mongoose: Mongoose;
options: FngOptions;
resources: Resource[];
searchFunc: typeof async.forEach;
constructor(mongoose: Mongoose, app: Express, options: FngOptions) {
this.mongoose = mongoose;
this.app = app;
app.locals.formsAngular = app.locals.formsAngular || [];
app.locals.formsAngular.push(this);
mongoose.set("debug", debug);
mongoose.Promise = global.Promise;
this.options = _.extend(
{
urlPrefix: "/api/",
},
options || {}
);
this.resources = [];
this.searchFunc = async.forEach;
// Do the plugin routes first
for (let pluginName in this.options.plugins) {
if (this.options.plugins.hasOwnProperty(pluginName)) {
let pluginObj: IFngPlugin = this.options.plugins[pluginName];
this.options.plugins[pluginName] = Object.assign(
this.options.plugins[pluginName],
pluginObj.plugin(this, processArgs, pluginObj.options)
);
}
}
const search = "search/",
schema = "schema/",
report = "report/",
resourceName = ":resourceName",
id = "/:id",
formName = "/:formName",
newClarifier = "/new";
this.app.get.apply(
this.app,
processArgs(this.options, ["models", this.models()])
);
this.app.get.apply(
this.app,
processArgs(this.options, [search + resourceName, this.search()])
);
this.app.get.apply(
this.app,
processArgs(this.options, [schema + resourceName, this.schema()])
);
this.app.get.apply(
this.app,
processArgs(this.options, [
schema + resourceName + formName,
this.schema(),
])
);
this.app.get.apply(
this.app,
processArgs(this.options, [report + resourceName, this.report()])
);
this.app.get.apply(
this.app,
processArgs(this.options, [
report + resourceName + "/:reportName",
this.report(),
])
);
this.app.get.apply(
this.app,
processArgs(this.options, [resourceName, this.collectionGet()])
);
// return the List attributes for all records. two endpoints that go through the same handler so permissions
// can be applied differently for the two use cases. /listAll is intended for listing records on a page;
// /picklistAll for listing them in a <select> or similar - used by record-handler's setUpLookupOptions() method, for cases
// where there's a lookup that doesn't use the fngajax option
this.app.get.apply(
this.app,
processArgs(this.options, [
resourceName + "/listAll",
this.entityListAll(),
])
);
this.app.get.apply(
this.app,
processArgs(this.options, [
resourceName + "/picklistAll",
this.entityListAll(),
])
);
// return the List attributes for a record - used by fng-ui-select
this.app.get.apply(
this.app,
processArgs(this.options, [
resourceName + id + "/list",
this.entityList(),
])
);
// 2x get, with and without formName
this.app.get.apply(
this.app,
processArgs(this.options, [resourceName + id, this.entityGet()])
);
this.app.get.apply(
this.app,
processArgs(this.options, [
resourceName + formName + id,
this.entityGet(),
])
); // We don't use the form name, but it can optionally be included so it can be referenced by the permissions check
// 3x post (for creating a new record), with and without formName, and in the case of without, with or without /new (which isn't needed if there's no formName)
this.app.post.apply(
this.app,
processArgs(this.options, [resourceName, this.collectionPost()])
);
this.app.post.apply(
this.app,
processArgs(this.options, [
resourceName + newClarifier,
this.collectionPost(),
])
);
this.app.post.apply(
this.app,
processArgs(this.options, [
resourceName + formName + newClarifier,
this.collectionPost(),
])
);
// 2x post and 2x put (for saving modifications to existing record), with and without formName
// (You can POST or PUT to update data)
this.app.post.apply(
this.app,
processArgs(this.options, [resourceName + id, this.entityPut()])
);
this.app.post.apply(
this.app,
processArgs(this.options, [
resourceName + formName + id,
this.entityPut(),
])
);
this.app.put.apply(
this.app,
processArgs(this.options, [resourceName + id, this.entityPut()])
);
this.app.put.apply(
this.app,
processArgs(this.options, [
resourceName + formName + id,
this.entityPut(),
])
);
// 2x delete, with and without formName
this.app.delete.apply(
this.app,
processArgs(this.options, [resourceName + id, this.entityDelete()])
);
this.app.delete.apply(
this.app,
processArgs(this.options, [
resourceName + formName + id,
this.entityDelete(),
])
);
this.app.get.apply(
this.app,
processArgs(this.options, ["search", this.searchAll()])
);
}
getFirstMatchingField(
resource: Resource,
doc: Document,
keyList: string[],
type?: string
) {
for (let i = 0; i < keyList.length; i++) {
let fieldDetails = resource.model.schema["tree"][keyList[i]];
if (
fieldDetails.type &&
(!type || fieldDetails.type.name === type) &&
keyList[i] !== "_id"
) {
resource.options.listFields = [{ field: keyList[i] }];
return doc ? doc[keyList[i]] : keyList[i];
}
}
}
getListFields(resource: Resource, doc: Document, cb) {
const that = this;
let display = "";
let listFields = resource.options.listFields;
if (listFields) {
async.map(
listFields,
function (aField, cbm) {
if (typeof doc[aField.field] !== "undefined") {
if (aField.params) {
if (aField.params.ref) {
let fieldOptions = (
resource.model.schema["paths"][aField.field] as any
).options;
if (typeof fieldOptions.ref === "string") {
let lookupResource = that.getResource(fieldOptions.ref);
if (lookupResource) {
let hiddenFields = that.generateHiddenFields(
lookupResource,
false
);
lookupResource.model
.findOne({ _id: doc[aField.field] })
.select(hiddenFields)
.exec()
.then((doc2) => {
that.getListFields(lookupResource, doc2, cbm);
})
.catch((err) => {
cbm(err);
});
}
} else {
throw new Error(
"No support for ref type " + aField.params.ref.type
);
}
} else if (aField.params.params === "timestamp") {
let date = that.extractTimestampFromMongoID(doc[aField.field]);
cbm(
null,
date.toLocaleDateString() + " " + date.toLocaleTimeString()
);
} else if (!aField.params.params) {
throw new Error(
`Missing idIsList params for resource ${resource.resourceName}: ${JSON.stringify(aField.params)}`
);
} else if (typeof doc[aField.params.params] === "function") {
const resultOrPromise = doc[aField.params.params]();
if (typeof resultOrPromise.then === "function") {
resultOrPromise.then((result: string) => cbm(null, result));
} else {
cbm(null, resultOrPromise);
}
} else {
throw new Error(
`No support for idIsList params for resource ${resource.resourceName}: ${JSON.stringify(aField.params)}`
);
}
} else {
cbm(null, doc[aField.field]);
}
} else {
cbm(null, "");
}
},
function (err, results) {
if (err) {
cb(err);
} else {
if (results) {
cb(err, results.join(" ").trim());
} else {
console.log("No results " + listFields);
}
}
}
);
} else {
const keyList = Object.keys(resource.model.schema["tree"]);
// No list field specified - use the first String field,
display =
this.getFirstMatchingField(resource, doc, keyList, "String") ||
// and if there aren't any then just take the first field
this.getFirstMatchingField(resource, doc, keyList);
cb(null, display.trim());
}
}
// generate a Mongo projection that can be used to restrict a query to return only those fields from the given
// resource that are identified as "list" fields (i.e., ones that should appear whenever records of that type are
// displayed in a list)
generateListFieldProjection(resource: Resource) {
const projection = {};
const listFields = resource.options?.listFields;
// resource.options.listFields will identify all of the fields from resource that have a value for .list.
// generally, that value will be "true", identifying the corresponding field as one which should be
// included whenever records of that type appear in a list.
// occasionally, it will instead be "{ ref: true }"", which means something entirely different -
// this means that the field requires a lookup translation before it can be displayed on a form.
// for our purposes, we're interested in only the first of these two cases, so we'll ignore anything where
// field.params.ref has a truthy value
if (listFields) {
for (const field of listFields) {
if (!field.params?.ref) {
projection[field.field] = 1;
}
}
} else {
const keyList = Object.keys(resource.model.schema["tree"]);
const firstField =
// No list field specified - use the first String field,
this.getFirstMatchingField(resource, undefined, keyList, "String") ||
// and if there aren't any then just take the first field
this.getFirstMatchingField(resource, undefined, keyList);
projection[firstField] = 1;
}
return projection;
}
newResource(model, options: ResourceOptions) {
options = options || {};
options.suppressDeprecatedMessage = true;
let passModel = model;
if (typeof model !== "function") {
passModel = model.model;
}
this.addResource(passModel.modelName, passModel, options);
}
// Add a resource, specifying the model and any options.
// Models may include their own options, which means they can be passed through from the model file
addResource(resourceName: string, model, options: ResourceOptions) {
let resource: Resource = {
resourceName: resourceName,
resourceNameLower: resourceName.toLowerCase(),
options: options || {},
};
if (!resource.options.suppressDeprecatedMessage) {
console.log(
"addResource is deprecated - see https://github.com/forms-angular/forms-angular/issues/39"
);
}
// Check all the synonyms are lower case
resource.options.synonyms?.forEach((s) => {
s.name = s.name.toLowerCase();
});
if (typeof model === "function") {
resource.model = model;
} else {
resource.model = model.model;
for (const prop in model) {
if (model.hasOwnProperty(prop) && prop !== "model") {
resource.options[prop] = model[prop];
}
}
}
extend(
resource.options,
this.preprocess(resource, resource.model.schema.paths)
);
resource.options.searchFields = [];
// commenting this out, as we used to do this in a place where the type of resource.model.schema was any,
// so it was allowed, despite the fact that _indexes is not a known property of a mongoose schema.
// changing it to indexes does compile, but this might not be what was intended
//
// for (let j = 0; j < resource.model.schema._indexes.length; j++) {
// let attributes = resource.model.schema._indexes[j][0];
// let field = Object.keys(attributes)[0];
// if (resource.options.searchFields.indexOf(field) === -1) {
// resource.options.searchFields.push(field);
// }
// }
function addSearchFields(schema: Schema, pathSoFar: string) {
for (let path in schema.paths) {
if (path !== "_id" && schema.paths.hasOwnProperty(path)) {
const qualifiedPath = pathSoFar ? pathSoFar + "." + path : path;
if (
schema.paths[path].options.index &&
!schema.paths[path].options.noSearch
) {
if (resource.options.searchFields.indexOf(qualifiedPath) === -1) {
resource.options.searchFields.push(qualifiedPath);
}
} else if (schema.paths[path].schema) {
addSearchFields(schema.paths[path].schema, qualifiedPath);
}
}
}
}
addSearchFields(resource.model.schema, "");
if (resource.options.searchImportance) {
this.searchFunc = async.forEachSeries;
}
if (this.searchFunc === async.forEachSeries) {
this.resources.splice(
_.sortedIndexBy(this.resources, resource, function (obj) {
return obj.options.searchImportance || 99;
}),
0,
resource
);
} else {
this.resources.push(resource);
}
}
getResource(name: string): Resource {
return _.find(this.resources, function (resource) {
return (
resource.resourceName === name || resource.options.resourceName === name
);
});
}
getResourceFromCollection(name: string): Resource {
return _.find(this.resources, function (resource) {
return resource.model.collection.collectionName === name;
});
}
// Using the given (already-populated) AmbiguousRecordStore, generate text suitable for
// disambiguation of each ambiguous record, and pass that to the given disambiguateItemCallback
// so our caller can decorate the ambiguous record in whatever way it deems appropriate.
//
// The ambiguousRecordStore provided to this function (generated either by a call to
// buildSingleResourceAmbiguousRecordStore() or buildMultiResourceAmbiguousRecordStore()) will
// already be grouping records by the resource that should be used to disambiguate them, with
// the name of that resource being the primary index property of the store.
//
// The disambiguation text will be the concatenation (space-seperated) of the list fields for
// the doc from that resource whose _id matches the value of record[disambiguationField].
//
// allRecords should include all of the ambiguous records (also held by AmbiguousRecordStore)
// as well as those found not to be ambiguous. The final act of this function will be to delete
// the disambiguation field from those records - it is only going to be there for the purpose
// of disambiguation, and should not be returned by our caller once disambiguation is complete.
//
// The scary-looking templating used here ensures that the objects in allRecords (and also
// ambiguousRecordStore) include an (optional) string property with the name identified by
// disambiguationField. For the avoidance of doubt, "prop" here could be anything - "foo in f"
// would achieve the same result.
disambiguate<t extends { [prop in f]?: string }, f extends string>(
allRecords: t[],
ambiguousRecordStore: fngServer.AmbiguousRecordStore<t>,
disambiguationField: f,
disambiguateItemCallback: (item: t, disambiguationText: string) => void,
completionCallback: (err) => void
): void {
const that = this;
async.map(
Object.keys(ambiguousRecordStore),
function (resourceName: string, cbm: (err) => void) {
const resource = that.getResource(resourceName);
const projection = that.generateListFieldProjection(resource);
resource.model
.find({
_id: {
$in: ambiguousRecordStore[resourceName].map(
(sr) => sr[disambiguationField]
),
},
})
.select(projection)
.lean()
.then((disambiguationRecs: any[]) => {
for (const ambiguousResult of ambiguousRecordStore[resourceName]) {
const disambiguator = disambiguationRecs.find(
(d) =>
d._id.toString() ===
ambiguousResult[disambiguationField].toString()
);
if (disambiguator) {
let suffix = "";
for (const listField in projection) {
if (disambiguator[listField]) {
if (suffix) {
suffix += " ";
}
suffix += disambiguator[listField];
}
}
if (suffix) {
disambiguateItemCallback(ambiguousResult, suffix);
}
}
}
cbm(null);
})
.catch((err) => {
cbm(err);
});
},
(err) => {
for (const record of allRecords) {
delete record[disambiguationField];
}
completionCallback(err);
}
);
}
internalSearch(
req,
resourcesToSearch,
includeResourceInResults,
limit,
callback
) {
if (typeof req.query === "undefined") {
req.query = {};
}
const timestamps = {
sentAt: req.query.sentAt,
startedAt: new Date().valueOf(),
completedAt: undefined,
};
let searches = [],
resourceCount = resourcesToSearch.length,
searchFor = req.query.q || "",
filter = req.query.f;
function translate(string, array, context) {
if (array) {
let translation = _.find(array, function (fromTo) {
return (
fromTo.from === string &&
(!fromTo.context || fromTo.context === context)
);
});
if (translation) {
string = translation.to;
}
}
return string;
}
// return a string that determines the sort order of the resultObject
function calcResultValue(obj) {
function padLeft(score: number, reqLength: number, str = "0") {
return (
new Array(1 + reqLength - String(score).length).join(str) + score
);
}
let sortString = "";
sortString += padLeft(obj.addHits || 9, 1);
sortString += padLeft(obj.searchImportance || 99, 2);
sortString += padLeft(obj.weighting || 9999, 4);
sortString += obj.text;
return sortString;
}
if (filter) {
filter = JSON.parse(filter);
}
// See if we are narrowing down the resources
let collectionName: string;
let collectionNameLower: string;
let colonPos = searchFor.indexOf(":");
switch (colonPos) {
case -1:
// Original behaviour = do nothing different
break;
case 0:
// "Special search" - yet to be implemented
break;
default:
collectionName = searchFor.slice(0, colonPos);
collectionNameLower = collectionName.toLowerCase();
searchFor = searchFor.slice(colonPos + 1, 999).trim();
if (searchFor === "") {
searchFor = "?";
}
break;
}
for (let i = 0; i < resourceCount; i++) {
let resource = resourcesToSearch[i];
if (
resourceCount === 1 ||
(resource.options.searchImportance !== false &&
(!collectionName ||
collectionNameLower === resource.resourceNameLower ||
resource.options?.synonyms?.find(
(s) => s.name === collectionNameLower
)))
) {
let searchFields = resource.options.searchFields;
if (searchFields.length === 0) {
console.log(
"ERROR: Searching on a collection with no indexes " +
resource.resourceName
);
}
let synonymObj = resource.options?.synonyms?.find(
(s) => s.name.toLowerCase() === collectionNameLower
);
const synonymFilter = synonymObj?.filter;
for (let m = 0; m < searchFields.length; m++) {
let searchObj: { resource: Resource; field: string; filter?: any } = {
resource: resource,
field: searchFields[m],
};
if (synonymFilter) {
searchObj.filter = synonymFilter;
}
searches.push(searchObj);
}
}
}
const that = this;
let results: IInternalSearchResult[] = [];
let moreCount = 0;
let searchCriteria;
let searchStrings;
let multiMatchPossible = false;
if (searchFor === "?") {
// interpret this as a wildcard (so there is no way to search for ?
searchCriteria = null;
} else {
// Support for searching anywhere in a field by starting with *
let startAnchor = "^";
if (searchFor.slice(0, 1) === "*") {
startAnchor = "";
searchFor = searchFor.slice(1);
}
// THe snippet to escape the special characters comes from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
searchFor = searchFor.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
multiMatchPossible = searchFor.includes(" ");
if (multiMatchPossible) {
searchStrings = searchFor.split(" ");
}
let modifiedSearchStr = multiMatchPossible
? searchStrings.join("|")
: searchFor;
searchFor = searchFor.toLowerCase(); // For later case-insensitive comparison
// Removed the logic that preserved spaces when collection was specified because Louise asked me to.
searchCriteria = {
$regex: `${startAnchor}(${modifiedSearchStr})`,
$options: "i",
};
}
let handleSearchResultsFromIndex = function (err, docs, item, cb) {
function handleSingleSearchResult(aDoc: Document, cbdoc) {
let thisId: string = aDoc._id.toString(),
resultObject: IInternalSearchResult,
resultPos: number;
function handleResultsInList() {
if (multiMatchPossible) {
resultObject.matched = resultObject.matched || [];
// record the index of string that matched, so we don't count it against another field
for (let i = 0; i < searchStrings.length; i++) {
if (
aDoc[item.field]?.toLowerCase().indexOf(searchStrings[i]) === 0
) {
resultObject.matched.push(i);
break;
}
}
}
resultObject.resourceCollection = item.resource.resourceName;
resultObject.searchImportance =
item.resource.options.searchImportance || 99;
if (item.resource.options.localisationData) {
resultObject.resource = translate(
resultObject.resource,
item.resource.options.localisationData,
"resource"
);
resultObject.resourceText = translate(
resultObject.resourceText,
item.resource.options.localisationData,
"resourceText"
);
resultObject.resourceTab = translate(
resultObject.resourceTab,
item.resource.options.localisationData,
"resourceTab"
);
}
results.splice(
_.sortedIndexBy(results, resultObject, calcResultValue),
0,
resultObject
);
cbdoc(null);
}
// Do we already have them in the list?
for (resultPos = results.length - 1; resultPos >= 0; resultPos--) {
// check for matching id and resource
if (results[resultPos].id.toString() === thisId && results[resultPos].resourceCollection === item.resource.resourceName) {
break;
}
}
if (resultPos >= 0) {
resultObject = Object.assign({}, results[resultPos]);
// If they have already matched then improve their weighting
if (multiMatchPossible) {
// record the index of string that matched, so we don't count it against another field
for (let i = 0; i < searchStrings.length; i++) {
if (
!resultObject.matched.includes(i) &&
aDoc[item.field]?.toLowerCase().indexOf(searchStrings[i]) === 0
) {
resultObject.matched.push(i);
resultObject.addHits = Math.max(
(resultObject.addHits || 9) - 1,
0
);
// remove it from current position
results.splice(resultPos, 1);
// and re-insert where appropriate
results.splice(
_.sortedIndexBy(results, resultObject, calcResultValue),
0,
resultObject
);
break;
}
}
}
cbdoc(null);
} else {
// Otherwise add them new...
let addHits: number;
if (multiMatchPossible) {
// If they match the whole search phrase in one index they get smaller addHits (so they sort higher)
if (aDoc[item.field]?.toLowerCase().indexOf(searchFor) === 0) {
addHits = 7;
}
}
let disambiguationId: any;
const opts = item.resource.options as fngServer.ResourceOptions;
const disambiguationResource = opts.disambiguation?.resource;
if (disambiguationResource) {
disambiguationId = aDoc[opts.disambiguation.field]?.toString();
}
// Use special listings format if defined
let specialListingFormat: ISearchResultFormatter =
item.resource.options.searchResultFormat;
if (specialListingFormat) {
specialListingFormat.apply(aDoc, [req]).then((resultObj) => {
resultObject = resultObj;
resultObject.addHits = addHits;
resultObject.disambiguationResource = disambiguationResource;
resultObject.disambiguationId = disambiguationId;
handleResultsInList();
});
} else {
that.getListFields(
item.resource,
aDoc,
function (err, description) {
if (err) {
cbdoc(err);
} else {
(resultObject as any) = {
id: aDoc._id,
weighting: 9999,
addHits,
disambiguationResource,
disambiguationId,
text: description,
};
if (resourceCount > 1 || includeResourceInResults) {
resultObject.resource = resultObject.resourceText =
item.resource.resourceName;
}
handleResultsInList();
}
}
);
}
}
}
if (!err && docs && docs.length > 0) {
async.map(docs, handleSingleSearchResult, cb);
} else {
cb(err);
}
};
this.searchFunc(
searches,
function (item, cb) {
let searchDoc = {};
let searchFilter = filter || item.filter;
if (searchFilter) {
that.hackVariables(searchFilter);
extend(searchDoc, searchFilter);
if (searchFilter[item.field]) {
delete searchDoc[item.field];
let obj1 = {},
obj2 = {};
obj1[item.field] = searchFilter[item.field];
obj2[item.field] = searchCriteria;
searchDoc["$and"] = [obj1, obj2];
} else {
if (searchCriteria) {
searchDoc[item.field] = searchCriteria;
}
}
} else {
if (searchCriteria) {
searchDoc[item.field] = searchCriteria;
}
}
/*
The +200 below line is an (imperfect) arbitrary safety zone for situations where items that match the string in more than one index get filtered out.
An example where it fails is searching for "e c" which fails to get a old record Emily Carpenter in a big dataset sorted by date last accessed as they
are not returned within the first 200 in forenames so don't get the additional hit score and languish outside the visible results, though those visible
results end up containing people who only match either c or e (but have been accessed much more recently).
Increasing the number would be a short term fix at the cost of slowing down the search.
*/
// TODO : Figure out a better way to deal with this
if (item.resource.options.searchFunc) {
item.resource.options.searchFunc(
item.resource,
req,
null,
searchDoc,
item.resource.options.searchOrder,
limit ? limit + 200 : 0,
null,
function (err, docs) {
handleSearchResultsFromIndex(err, docs, item, cb);
}
);
} else {
that.filteredFind(
item.resource,
req,
null,
searchDoc,
null,
item.resource.options.searchOrder,
limit ? limit + 200 : 0,
null,
function (err, docs) {
handleSearchResultsFromIndex(err, docs, item, cb);
}
);
}
},
function (err) {
if (err) {
callback(err);
} else {
// Strip weighting from the results
results = _.map(results, function (aResult) {
delete aResult.weighting;
return aResult;
});
if (limit && results.length > limit) {
moreCount += results.length - limit;
results.splice(limit);
}
that.disambiguate(
results,
that.buildMultiResourceAmbiguousRecordStore(
results,
["text"],
"disambiguationResource"
),
"disambiguationId",
(item: IInternalSearchResult, disambiguationText: string) => {
item.text += ` (${disambiguationText})`;
},
(err) => {
if (err) {
callback(err);
} else {
// the disambiguate() call will have deleted the disambiguationIds but we're responsible for
// the disambiguationResources, which we shouldn't be returning to the client
for (const result of results) {
delete result.disambiguationResource;
}
timestamps.completedAt = new Date().valueOf();
callback(null, { results, moreCount, timestamps });
}
}
);
}
}
);
}
wrapInternalSearch(
req: Express.Request,
res: Express.Response,
resourcesToSearch,
includeResourceInResults,
limit
) {
this.internalSearch(
req,
resourcesToSearch,
includeResourceInResults,
limit,
function (err, resultsObject) {
if (err) {
res.status(400, err);
} else {
res.send(resultsObject);
}
}
);