forked from paularmstrong/normalizr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelationships.ts
53 lines (47 loc) · 1.08 KB
/
relationships.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
import { normalize, schema } from '../index'
const userProcessStrategy = (value: any, parent: any, key: string) => {
switch (key) {
case 'author':
return { ...value, posts: [parent.id] };
case 'commenter':
return { ...value, comments: [parent.id] };
default:
return { ...value };
}
};
const userMergeStrategy = (entityA: any, entityB: any) => {
return {
...entityA,
...entityB,
posts: [...(entityA.posts || []), ...(entityB.posts || [])],
comments: [...(entityA.comments || []), ...(entityB.comments || [])]
};
};
const user = new schema.Entity(
'users',
{},
{
mergeStrategy: userMergeStrategy,
processStrategy: userProcessStrategy
}
);
const comment = new schema.Entity(
'comments',
{
commenter: user
},
{
processStrategy: (value: any, parent: any, key: string) => {
return { ...value, post: parent.id };
}
}
);
const post = new schema.Entity('posts', {
author: user,
comments: [comment]
});
const data = {
/* ...*/
};
const normalizedData = normalize(data, post);
console.log(normalizedData);