utils.tsx 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import {Query} from 'history';
  2. import cloneDeep from 'lodash/cloneDeep';
  3. import pick from 'lodash/pick';
  4. import {GlobalSelection} from 'app/types';
  5. import {getUtcDateString} from 'app/utils/dates';
  6. import EventView from 'app/utils/discover/eventView';
  7. import {DashboardDetails, DisplayType, Widget, WidgetQuery} from './types';
  8. export function cloneDashboard(dashboard: DashboardDetails): DashboardDetails {
  9. return cloneDeep(dashboard);
  10. }
  11. export function eventViewFromWidget(
  12. title: string,
  13. query: WidgetQuery,
  14. selection: GlobalSelection,
  15. widgetType?: DisplayType
  16. ): EventView {
  17. const {start, end, period: statsPeriod} = selection.datetime;
  18. const {projects, environments} = selection;
  19. // World Map requires an additional column (geo.country_code) to display in discover when navigating from the widget
  20. const fields =
  21. widgetType === DisplayType.WORLD_MAP
  22. ? ['geo.country_code', ...query.fields]
  23. : query.fields;
  24. const conditions =
  25. widgetType === DisplayType.WORLD_MAP
  26. ? `${query.conditions} has:geo.country_code`
  27. : query.conditions;
  28. return EventView.fromSavedQuery({
  29. id: undefined,
  30. name: title,
  31. version: 2,
  32. fields,
  33. query: conditions,
  34. orderby: query.orderby,
  35. projects,
  36. range: statsPeriod,
  37. start: start ? getUtcDateString(start) : undefined,
  38. end: end ? getUtcDateString(end) : undefined,
  39. environment: environments,
  40. });
  41. }
  42. function coerceStringToArray(value?: string | string[] | null) {
  43. return typeof value === 'string' ? [value] : value;
  44. }
  45. export function constructWidgetFromQuery(query?: Query): Widget | undefined {
  46. if (query) {
  47. const queryNames = coerceStringToArray(query.queryNames);
  48. const queryConditions = coerceStringToArray(query.queryConditions);
  49. const queryFields = coerceStringToArray(query.queryFields);
  50. const queries: WidgetQuery[] = [];
  51. if (
  52. queryConditions &&
  53. queryNames &&
  54. queryFields &&
  55. typeof query.queryOrderby === 'string'
  56. )
  57. queryConditions.forEach((condition, index) => {
  58. queries.push({
  59. name: queryNames[index],
  60. conditions: condition,
  61. fields: queryFields,
  62. orderby: query.queryOrderby as string,
  63. });
  64. });
  65. if (query.title && query.displayType && query.interval && queries.length > 0) {
  66. const newWidget: Widget = {
  67. ...(pick(query, ['title', 'displayType', 'interval']) as {
  68. title: string;
  69. displayType: DisplayType;
  70. interval: string;
  71. }),
  72. queries,
  73. };
  74. return newWidget;
  75. }
  76. }
  77. return undefined;
  78. }