formatMongoDBQuery.tsx 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. if (isBoldedEntry) {
  42. tokens.push(jsonEntryToToken(key, val, true));
  43. } else {
  44. tempTokens.push(jsonEntryToToken(key, val));
  45. }
  46. });
  47. if (tokens.length === 1 && tempTokens.length > 0) {
  48. tokens.push(stringToToken(', ', `${tokens[0]!.key}:,`));
  49. }
  50. tempTokens.forEach((token, index) => {
  51. tokens.push(token);
  52. if (index !== tempTokens.length - 1) {
  53. tokens.push(stringToToken(', ', `${token.key}:${index}`));
  54. }
  55. });
  56. sentrySpan.end();
  57. return tokens;
  58. }
  59. function jsonEntryToToken(key: string, value: JSONValue, isBold?: boolean) {
  60. const tokenString = jsonToTokenizedString(value, key);
  61. return stringToToken(tokenString, `${key}:${value}`, isBold);
  62. }
  63. function jsonToTokenizedString(value: JSONValue | JSONValue[], key?: string): string {
  64. let result = '';
  65. if (key) {
  66. result = `"${key}": `;
  67. }
  68. // Case 1: Value is null
  69. if (!value) {
  70. result += 'null';
  71. return result;
  72. }
  73. // Case 2: Value is a string
  74. if (typeof value === 'string') {
  75. result += `"${value}"`;
  76. return result;
  77. }
  78. // Case 3: Value is one of the other primitive types
  79. if (typeof value === 'number' || typeof value === 'boolean') {
  80. result += `${value}`;
  81. return result;
  82. }
  83. // Case 4: Value is an array
  84. if (Array.isArray(value)) {
  85. result += '[';
  86. value.forEach((item, index) => {
  87. if (index === value.length - 1) {
  88. result += jsonToTokenizedString(item);
  89. } else {
  90. result += `${jsonToTokenizedString(item)}, `;
  91. }
  92. });
  93. result += ']';
  94. return result;
  95. }
  96. // Case 5: Value is an object
  97. if (typeof value === 'object') {
  98. const entries = Object.entries(value);
  99. if (entries.length === 0) {
  100. result += '{}';
  101. return result;
  102. }
  103. result += '{ ';
  104. entries.forEach(([_key, val], index) => {
  105. if (index === entries.length - 1) {
  106. result += jsonToTokenizedString(val, _key);
  107. } else {
  108. result += `${jsonToTokenizedString(val, _key)}, `;
  109. }
  110. });
  111. result += ' }';
  112. return result;
  113. }
  114. // This branch should never be reached
  115. return '';
  116. }
  117. function stringToToken(str: string, keyProp: string, isBold?: boolean): ReactElement {
  118. return isBold ? <b key={keyProp}>{str}</b> : <span key={keyProp}>{str}</span>;
  119. }