query.service.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import * as fs from 'fs'
  2. import { isObject, get } from 'lodash'
  3. import { Observable, Subject, interval, map, of } from 'rxjs'
  4. import { DataPrepService } from './dataprep.service'
  5. import _ = require("lodash")
  6. export class SearchService {
  7. private dataPrepService : DataPrepService
  8. constructor(){
  9. this.dataPrepService = new DataPrepService()
  10. }
  11. public callFromOtherClass(){
  12. const t0 = performance.now()
  13. let i
  14. for (i = 0; i <= 6000000000; i++) {
  15. }
  16. const t1 = performance.now()
  17. const timeTakenInSeconds = (t1 - t0) / 1000;
  18. console.log(`Time taken: ${timeTakenInSeconds} seconds to run this function`);
  19. }
  20. public query(storageAddress: Storage, ...conditions: Conditions[]): Observable<any> {
  21. let dataFromStorage: Subject<any> = new Subject()
  22. let filteredResult: Subject<any> = new Subject()
  23. this.dataPrepService.loadObsData(storageAddress, dataFromStorage)
  24. this.filterFromObs(dataFromStorage, filteredResult, ...conditions)
  25. return filteredResult.pipe()
  26. }
  27. // Search and Filter: Pure Observables
  28. private filterFromObs(dataFromStorage: Subject<any>, filteredResult: Subject<any>, ...conditions: Conditions[]) {
  29. dataFromStorage.subscribe({
  30. next: element => {
  31. if (this.filterByKeyValue(element, ...conditions)) {
  32. filteredResult.next(element)
  33. } else {
  34. console.log(`${element.appData.msgId} does not match search criteria`)
  35. }
  36. }
  37. })
  38. }
  39. // Logic 1: Success. But argument must specifies header.messageID.... to search
  40. private hasMatchingProps(data, condition): boolean {
  41. // Merge all condtions into searchObj
  42. let result = _.every(condition, (val, key) => {
  43. const propKeys = key.split('.');
  44. let nestedObj = data;
  45. _.forEach(propKeys, propKey => {
  46. nestedObj = nestedObj[propKey];
  47. });
  48. if (_.isObject(val)) {
  49. return this.hasMatchingProps(nestedObj, val);
  50. }
  51. return nestedObj === val;
  52. });
  53. return result
  54. }
  55. // Logic 2: Success: More superior version than Logic 1 since it can perform flat searches like {messageID : 1234}
  56. // without specifying its parent property's name. eg: {header.messageID: 1234}
  57. private filterByKeyValue(data, ...conditions): boolean {
  58. try {
  59. // Merge all conditions into searchObj
  60. let searchObj = Object.assign({}, ...conditions)
  61. let recordFound = true
  62. // Check for data type. Can actually remove this code if dont want. Not that important anyways
  63. if (typeof data !== 'object' || typeof searchObj !== 'object') {
  64. return false;
  65. }
  66. // Check data to see if the given data is within the date range of the specified column
  67. if (recordFound == true) {
  68. if (searchObj.hasOwnProperty("$dateRange")) {
  69. recordFound = this.filterByDateRange(data, searchObj.$dateRange)
  70. delete searchObj.$dateRange
  71. }
  72. }
  73. // Check if the regular expression value matches any of the data string
  74. if (recordFound == true) {
  75. if (searchObj.hasOwnProperty("$regex")) {
  76. recordFound = this.filterViaRegex(data, searchObj.$regex)
  77. delete searchObj.$regex
  78. }
  79. }
  80. // Check if the key has parent key notation and then perform matching sequences. Eg : "header.appdata. etc etc"
  81. if (recordFound == true) {
  82. // check if key is header.is like 'propertyName1.propertyName2'
  83. let searchkey = Object.keys(searchObj)
  84. searchkey.every((key) => {
  85. if (key.includes('.')) {
  86. let condition = {
  87. key: searchObj[key]
  88. }
  89. this.hasMatchingProps(data, condition)
  90. delete searchObj[key]
  91. }
  92. })
  93. }
  94. // Check the rest of the key value pairs to see if the conditions are fulfilled(entries must matched)
  95. if (recordFound == true) {
  96. recordFound = this.matchValues(data, searchObj)
  97. }
  98. return recordFound
  99. }
  100. catch (e) {
  101. console.error(e.message)
  102. }
  103. }
  104. // Match the key values pair between conditions and the given data
  105. private matchValues(data, searchObj): boolean {
  106. let matchKeys = Object.keys(searchObj);
  107. let isMatchingObject = (object) => {
  108. return matchKeys.every((key) => {
  109. let lodashPath = key.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '');
  110. let objectValue = _.get(object, lodashPath);
  111. let searchValue = searchObj[key];
  112. if (Array.isArray(searchValue)) {
  113. // Check if any of the search values are included in the object value
  114. return searchValue.some((value) => {
  115. return Array.isArray(objectValue) ? objectValue.includes(value) : objectValue === value;
  116. });
  117. } else if (typeof searchValue === 'object' && typeof objectValue === 'object') {
  118. return isMatchingObject(objectValue);
  119. } else {
  120. return objectValue === searchValue;
  121. }
  122. });
  123. };
  124. let isObjectMatching = (object) => {
  125. if (typeof object !== 'object') {
  126. return false;
  127. }
  128. return isMatchingObject(object) || Object.values(object).some(isObjectMatching);
  129. };
  130. return isObjectMatching(data);
  131. }
  132. // Matching the regex args to see if it matches the data that is now converted to string. As long as partial match, it will return true
  133. private filterViaRegex(element: any, inquiry: any): boolean {
  134. // create a new regular expression to use regex.test
  135. const regex = new RegExp(inquiry);
  136. const hasMatchingSubstring = regex.test(JSON.stringify(element));
  137. return hasMatchingSubstring;
  138. }
  139. // Check if the data's date is within the date range provided and also the column in which the data is to be compared with
  140. private filterByDateRange(data: any, dateRange: DateRange): boolean {
  141. // Lodash implemetation to get the specific property of data
  142. let msgDate: string = get(data, dateRange.column)
  143. let date = new Date(msgDate)
  144. const start = new Date(dateRange.startDate);
  145. const end = new Date(dateRange.endDate);
  146. return date >= start && date <= end;
  147. }
  148. }
  149. // Entries that client will use. Subject to be improved later on
  150. export interface Conditions {
  151. $regex?: string,
  152. $dateRange?: DateRange,
  153. [key: string]: string | Date | DateRange | string[]
  154. }
  155. export interface DateRange {
  156. startDate: string | Date,
  157. endDate: string | Date,
  158. column: string
  159. }
  160. export interface StorageLocation {
  161. type: string,
  162. url: string
  163. }
  164. export interface ObservableStorage {
  165. type: "observable",
  166. ref: Observable<any>
  167. }
  168. export type Storage = StorageLocation| ObservableStorage