summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/import_entities/import_groups/graphql/services/status_poller.js
blob: 41dd25b9150b85abfb564de0aa2d1e3a1d01c08d (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
import gql from 'graphql-tag';
import createFlash from '~/flash';
import { s__ } from '~/locale';
import bulkImportSourceGroupsQuery from '../queries/bulk_import_source_groups.query.graphql';
import { STATUSES } from '../../../constants';
import { SourceGroupsManager } from './source_groups_manager';

const groupId = (i) => `group${i}`;

function generateGroupsQuery(groups) {
  return gql`{
    ${groups
      .map(
        (g, idx) =>
          `${groupId(idx)}: group(fullPath: "${g.import_target.target_namespace}/${
            g.import_target.new_name
          }") { id }`,
      )
      .join('\n')}
  }`;
}

export class StatusPoller {
  constructor({ client, interval }) {
    this.client = client;
    this.interval = interval;
    this.timeoutId = null;
    this.groupManager = new SourceGroupsManager({ client });
  }

  startPolling() {
    if (this.timeoutId) {
      return;
    }

    this.checkPendingImports();
  }

  stopPolling() {
    clearTimeout(this.timeoutId);
    this.timeoutId = null;
  }

  async checkPendingImports() {
    try {
      const { bulkImportSourceGroups } = this.client.readQuery({
        query: bulkImportSourceGroupsQuery,
      });
      const groupsInProgress = bulkImportSourceGroups.filter((g) => g.status === STATUSES.STARTED);
      if (groupsInProgress.length) {
        const { data: results } = await this.client.query({
          query: generateGroupsQuery(groupsInProgress),
          fetchPolicy: 'no-cache',
        });
        const completedGroups = groupsInProgress.filter((_, idx) => Boolean(results[groupId(idx)]));
        completedGroups.forEach((group) => {
          this.groupManager.setImportStatus(group, STATUSES.FINISHED);
        });
      }
    } catch (e) {
      createFlash({
        message: s__('BulkImport|Update of import statuses with realtime changes failed'),
      });
    } finally {
      this.timeoutId = setTimeout(() => this.checkPendingImports(), this.interval);
    }
  }
}