stream.tsx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * Converts a stream query to an object representation, with
  3. * keys representing tag names, and the magic __text key
  4. * representing the text component of the search.
  5. *
  6. * Example:
  7. *
  8. * "python is:unresolved assigned:foo@bar.com"
  9. * => {
  10. * __text: "python",
  11. * is: "unresolved",
  12. * assigned: "foo@bar.com"
  13. * }
  14. */
  15. export type QueryObj = Record<string, string>;
  16. export function queryToObj(queryStr = ''): QueryObj {
  17. const text: string[] = [];
  18. const queryItems = queryStr.match(/\S+:"[^"]*"?|\S+/g);
  19. const queryObj: QueryObj = (queryItems || []).reduce((obj, item) => {
  20. const index = item.indexOf(':');
  21. if (index === -1) {
  22. text.push(item);
  23. } else {
  24. const tagKey = item.slice(0, index);
  25. const value = item.slice(index + 1).replace(/^"|"$/g, '');
  26. obj[tagKey] = value;
  27. }
  28. return obj;
  29. }, {});
  30. queryObj.__text = '';
  31. if (text.length) {
  32. queryObj.__text = text.join(' ');
  33. }
  34. return queryObj;
  35. }
  36. /**
  37. * Converts an object representation of a stream query to a string
  38. * (consumable by the Sentry stream HTTP API).
  39. */
  40. export function objToQuery(queryObj: QueryObj): string {
  41. const {__text, ...tags} = queryObj;
  42. const parts = Object.entries(tags).map(([tagKey, value]) => {
  43. if (value.indexOf(' ') > -1) {
  44. value = `"${value}"`;
  45. }
  46. return `${tagKey}:${value}`;
  47. });
  48. if (queryObj.__text) {
  49. parts.push(queryObj.__text);
  50. }
  51. return parts.join(' ');
  52. }