summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/alerts_settings/utils/cache_updates.js
blob: 2e64312b0e0de08b5c121f193bb7441be0eb9abc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import produce from 'immer';
import { createAlert } from '~/flash';

import { DELETE_INTEGRATION_ERROR, ADD_INTEGRATION_ERROR } from './error_messages';

const deleteIntegrationFromStore = (store, query, { httpIntegrationDestroy }, variables) => {
  const integration = httpIntegrationDestroy?.integration;
  if (!integration) {
    return;
  }

  const sourceData = store.readQuery({
    query,
    variables,
  });

  const data = produce(sourceData, (draftData) => {
    draftData.project.alertManagementIntegrations.nodes = draftData.project.alertManagementIntegrations.nodes.filter(
      ({ id }) => id !== integration.id,
    );
  });

  store.writeQuery({
    query,
    variables,
    data,
  });
};

const addIntegrationToStore = (
  store,
  query,
  { httpIntegrationCreate, prometheusIntegrationCreate },
  variables,
) => {
  const integration =
    httpIntegrationCreate?.integration || prometheusIntegrationCreate?.integration;
  if (!integration) {
    return;
  }

  const sourceData = store.readQuery({
    query,
    variables,
  });

  const data = produce(sourceData, (draftData) => {
    draftData.project.alertManagementIntegrations.nodes = [
      integration,
      ...draftData.project.alertManagementIntegrations.nodes,
    ];
  });

  store.writeQuery({
    query,
    variables,
    data,
  });
};

const onError = (data, message) => {
  createAlert({ message });
  throw new Error(data.errors);
};

export const hasErrors = ({ errors = [] }) => errors?.length;

export const updateStoreAfterIntegrationDelete = (store, query, data, variables) => {
  if (hasErrors(data)) {
    onError(data, DELETE_INTEGRATION_ERROR);
  } else {
    deleteIntegrationFromStore(store, query, data, variables);
  }
};

export const updateStoreAfterIntegrationAdd = (store, query, data, variables) => {
  if (hasErrors(data)) {
    onError(data, ADD_INTEGRATION_ERROR);
  } else {
    addIntegrationToStore(store, query, data, variables);
  }
};