summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/import_entities/import_groups/graphql/services/source_groups_manager.js
blob: 047b04fe7d68c7d192bf2834cc75aab89ffa136f (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
import { defaultDataIdFromObject } from 'apollo-cache-inmemory';
import produce from 'immer';
import ImportSourceGroupFragment from '../fragments/bulk_import_source_group_item.fragment.graphql';

function extractTypeConditionFromFragment(fragment) {
  return fragment.definitions[0]?.typeCondition.name.value;
}

function generateGroupId(id) {
  return defaultDataIdFromObject({
    __typename: extractTypeConditionFromFragment(ImportSourceGroupFragment),
    id,
  });
}

export class SourceGroupsManager {
  constructor({ client }) {
    this.client = client;
  }

  findById(id) {
    const cacheId = generateGroupId(id);
    return this.client.readFragment({ fragment: ImportSourceGroupFragment, id: cacheId });
  }

  update(group, fn) {
    this.client.writeFragment({
      fragment: ImportSourceGroupFragment,
      id: generateGroupId(group.id),
      data: produce(group, fn),
    });
  }

  updateById(id, fn) {
    const group = this.findById(id);
    this.update(group, fn);
  }

  setImportStatus(group, status) {
    this.update(group, (sourceGroup) => {
      // eslint-disable-next-line no-param-reassign
      sourceGroup.status = status;
    });
  }
}