-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcache.ts
57 lines (42 loc) · 1.68 KB
/
cache.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import {
IDeserializeCache, TAnyKeyValueObject, TJsonaModel, TJsonApiData, TResourceIdObj
} from './JsonaTypes';
export function jsonStringify(json: TAnyKeyValueObject): string {
let stringified;
try {
stringified = JSON.stringify(json);
} catch (e) {
stringified = '';
console.warn(e);
}
return stringified;
}
export class DeserializeCache implements IDeserializeCache {
protected cachedModels = {};
getCachedModel(data:TJsonApiData, resourceIdObject: TResourceIdObj) {
const entityKey = this.createCacheKey(data, resourceIdObject);
return this.cachedModels[entityKey] || null;
}
handleModel(model: TJsonaModel, data: TJsonApiData, resourceIdObject: TResourceIdObj) {
const entityKey = this.createCacheKey(data, resourceIdObject);
const dataWithPayload = data.attributes || data.relationships;
if (entityKey && dataWithPayload) {
this.cachedModels[entityKey] = model;
}
}
createCacheKey(data, resourceIdObject?: TResourceIdObj) {
// resourceIdObject.meta sets to model in simplePropertyMappers.ts, so it should be used here too
// cache in this case probably will be redundant
if (!data.id || !data.type) {
return;
}
let resourcePart = resourceIdObject ? `${resourceIdObject.type}-${resourceIdObject.id}` : '';
if (resourceIdObject?.meta) {
resourcePart += `-${jsonStringify(resourceIdObject.meta)}`;
}
if (data.meta) {
return `${data.type}-${data.id}-${jsonStringify(data.meta)}-${resourcePart}`;
}
return `${data.type}-${data.id}-${resourcePart}`;
}
}