forked from apollographql/apollo-cache-persist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersistenceMapper.ts
35 lines (28 loc) · 884 Bytes
/
persistenceMapper.ts
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
export const persistenceMapper = async (data: any) => {
const parsed = JSON.parse(data);
const mapped: any = {};
const persistEntities: any[] = [];
const rootQuery = parsed['ROOT_QUERY'];
mapped['ROOT_QUERY'] = Object.keys(rootQuery).reduce(
(obj: any, key: string) => {
if (key === '__typename') return obj;
if (/@persist$/.test(key)) {
obj[key] = rootQuery[key];
if (Array.isArray(rootQuery[key])) {
const entities = rootQuery[key].map((item: any) => item.__ref);
persistEntities.push(...entities);
} else {
const entity = rootQuery[key].__ref;
persistEntities.push(entity);
}
}
return obj;
},
{__typename: 'Query'},
);
persistEntities.reduce((obj, key) => {
obj[key] = parsed[key];
return obj;
}, mapped);
return JSON.stringify(mapped);
};