query.service.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import * as fs from 'fs'
  2. import { _, isObject, get } from 'lodash'
  3. import { Observable, Subject, interval, map, of } from 'rxjs'
  4. export class queryService {
  5. public query(storageAddress: Storage, ...conditions: Conditions[]): Observable<any> {
  6. let dataFromStorage: Subject<any> = new Subject()
  7. let filteredResult: Subject<any> = new Subject()
  8. this.loadObsData(storageAddress.address, dataFromStorage)
  9. this.filterFromObs(dataFromStorage, filteredResult, ...conditions)
  10. return filteredResult.pipe()
  11. }
  12. // Data preparations: Purely Observables
  13. private loadObsData(location: string, dataFromStorage: Subject<any>) {
  14. // Temporary version. More defined design will be implemented to cater for different storage locations
  15. let data = fs.readFileSync(location, 'utf-8')
  16. let dataJson = JSON.parse(data)
  17. let count = 0
  18. const intervalId = setInterval(() => {
  19. dataFromStorage.next(dataJson[count]);
  20. count++;
  21. if (count >= 100) {
  22. clearInterval(intervalId);
  23. dataFromStorage.complete();
  24. }
  25. }, 250)
  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.header.messageName} 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. $msgTag?: string[],
  154. [key: string]: string | Date | DateRange | string[]
  155. }
  156. export interface DateRange {
  157. startDate: string | Date,
  158. endDate: string | Date,
  159. column: string
  160. }
  161. export interface Storage {
  162. type: string,
  163. address: string
  164. }