formatMongoDBQuery.tsx 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import type {ReactElement} from 'react';
  2. import * as Sentry from '@sentry/react';
  3. import {jsonrepair} from 'jsonrepair';
  4. type JSONValue = string | number | object | boolean | null;
  5. /**
  6. * Takes in a MongoDB query JSON string and outputs it as HTML tokens.
  7. * Performs some processing to surface the DB operation and collection so they are the first key-value
  8. * pair in the query, and **bolds** the operation
  9. *
  10. * @param query The query as a JSON string
  11. * @param command The DB command, e.g. `find`. This is available as a tag on database spans
  12. */
  13. export function formatMongoDBQuery(query: string, command: string) {
  14. const sentrySpan = Sentry.startInactiveSpan({
  15. op: 'function',
  16. name: 'formatMongoDBQuery',
  17. attributes: {
  18. query,
  19. command,
  20. },
  21. onlyIfParent: true,
  22. });
  23. let queryObject: Record<string, JSONValue> = {};
  24. try {
  25. queryObject = JSON.parse(query);
  26. } catch {
  27. try {
  28. const repairedJson = jsonrepair(query);
  29. queryObject = JSON.parse(repairedJson);
  30. } catch {
  31. return query;
  32. }
  33. }
  34. const tokens: ReactElement[] = [];
  35. const tempTokens: ReactElement[] = [];
  36. const queryEntries = Object.entries(queryObject);
  37. queryEntries.forEach(([key, val]) => {
  38. const isBoldedEntry = key.toLowerCase() === command.toLowerCase();
  39. // Push the bolded entry into tokens so it is the first entry displayed.
  40. // The other tokens will be pushed into tempTokens, and then copied into tokens afterwards
  41. isBoldedEntry
  42. ? tokens.push(jsonEntryToToken(key, val, true))
  43. : tempTokens.push(jsonEntryToToken(key, val));
  44. });
  45. if (tokens.length === 1 && tempTokens.length > 0) {
  46. tokens.push(stringToToken(', ', `${tokens[0].key}:,`));
  47. }
  48. tempTokens.forEach((token, index) => {
  49. tokens.push(token);
  50. if (index !== tempTokens.length - 1) {
  51. tokens.push(stringToToken(', ', `${token.key}:${index}`));
  52. }
  53. });
  54. sentrySpan.end();
  55. return tokens;
  56. }
  57. function jsonEntryToToken(key: string, value: JSONValue, isBold?: boolean) {
  58. const tokenString = jsonToTokenizedString(value, key);
  59. return stringToToken(tokenString, `${key}:${value}`, isBold);
  60. }
  61. function jsonToTokenizedString(value: JSONValue | JSONValue[], key?: string): string {
  62. let result = '';
  63. if (key) {
  64. result = `"${key}": `;
  65. }
  66. // Case 1: Value is null
  67. if (!value) {
  68. result += 'null';
  69. return result;
  70. }
  71. // Case 2: Value is a string
  72. if (typeof value === 'string') {
  73. result += `"${value}"`;
  74. return result;
  75. }
  76. // Case 3: Value is one of the other primitive types
  77. if (typeof value === 'number' || typeof value === 'boolean') {
  78. result += `${value}`;
  79. return result;
  80. }
  81. // Case 4: Value is an array
  82. if (Array.isArray(value)) {
  83. result += '[';
  84. value.forEach((item, index) => {
  85. if (index === value.length - 1) {
  86. result += jsonToTokenizedString(item);
  87. } else {
  88. result += `${jsonToTokenizedString(item)}, `;
  89. }
  90. });
  91. result += ']';
  92. return result;
  93. }
  94. // Case 5: Value is an object
  95. if (typeof value === 'object') {
  96. const entries = Object.entries(value);
  97. if (entries.length === 0) {
  98. result += '{}';
  99. return result;
  100. }
  101. result += '{ ';
  102. entries.forEach(([_key, val], index) => {
  103. if (index === entries.length - 1) {
  104. result += jsonToTokenizedString(val, _key);
  105. } else {
  106. result += `${jsonToTokenizedString(val, _key)}, `;
  107. }
  108. });
  109. result += ' }';
  110. return result;
  111. }
  112. // This branch should never be reached
  113. return '';
  114. }
  115. function stringToToken(str: string, keyProp: string, isBold?: boolean): ReactElement {
  116. return isBold ? <b key={keyProp}>{str}</b> : <span key={keyProp}>{str}</span>;
  117. }