blob: 8fc7c69c79df628511b5b9a79a807d5b2b61483f (
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
|
// this file is based on https://github.com/apollographql/apollo-cache-persist/blob/master/examples/react-native/src/utils/persistence/persistenceMapper.ts
// with some heavy refactororing
/* eslint-disable @gitlab/require-i18n-strings */
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-param-reassign */
/* eslint-disable dot-notation */
export const persistenceMapper = async (data) => {
const parsed = JSON.parse(data);
const mapped = {};
const persistEntities = [];
const rootQuery = parsed['ROOT_QUERY'];
// cache entities that have `__persist: true`
Object.keys(parsed).forEach((key) => {
if (parsed[key]['__persist']) {
persistEntities.push(key);
}
});
// cache root queries that have `@persist` directive
mapped['ROOT_QUERY'] = Object.keys(rootQuery).reduce(
(obj, key) => {
if (key === '__typename') return obj;
if (/@persist$/.test(key)) {
obj[key] = rootQuery[key];
if (Array.isArray(rootQuery[key])) {
const entities = rootQuery[key].map((item) => item.__ref);
persistEntities.push(...entities);
} else {
const entity = rootQuery[key].__ref;
persistEntities.push(entity);
}
}
return obj;
},
{ __typename: 'Query' },
);
persistEntities.reduce((obj, key) => {
const parsedEntity = parsed[key];
// check for root queries and only cache root query properties that have `__persist: true`
// we need this to prevent overcaching when we fetch the same entity (e.g. project) more than once
// with different set of fields
if (Object.values(rootQuery).some((value) => value.__ref === key)) {
const mappedEntity = {};
Object.entries(parsedEntity).forEach(([parsedKey, parsedValue]) => {
if (!parsedValue || typeof parsedValue !== 'object' || parsedValue['__persist']) {
mappedEntity[parsedKey] = parsedValue;
}
});
obj[key] = mappedEntity;
} else {
obj[key] = parsed[key];
}
return obj;
}, mapped);
return JSON.stringify(mapped);
};
|