-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
resource-recursion.example.ts
89 lines (83 loc) · 2.52 KB
/
resource-recursion.example.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Linker, Serializer, Relator, Metaizer, Paginator } from '../src';
import { User, Article, Comment } from '../test/models';
import { getJSON } from '../test/utils/get-json';
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* SETUP */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
for (let i = 0; i < 5; i++) {
User.save(new User(String(i)));
}
for (let i = 0; i < 5; i++) {
Article.save(new Article(String(i), User.storage[0]));
}
for (let i = 0; i < 10; i++) {
Comment.save(new Comment(String(i), Article.storage[0], User.storage[0]));
}
let UserSerializer = new Serializer<User>('users', {
depth: 0, // Change to 2 to see the difference
});
let CommentSerializer = new Serializer<Comment>('comments');
let ArticleSerializer = new Serializer<Article>('articles');
const UserArticleRelator = new Relator(async (user: User) => user.getArticles(), ArticleSerializer);
const ArticleCommentRelator = new Relator(
async (article: Article) => article.getComments(),
CommentSerializer
);
const CommentUserRelator = new Relator(
async (comment: Comment) => comment.getAuthor(),
UserSerializer
);
CommentSerializer.setRelators(CommentUserRelator);
UserSerializer.setRelators(UserArticleRelator);
ArticleSerializer.setRelators(ArticleCommentRelator);
/* -------------------------------------------------------------------------- */
(async () => {
const user = User.storage[0];
const document = await UserSerializer.serialize(user);
console.dir(getJSON(document));
// Output: {
// jsonapi: { version: "1.0" },
// included: [
// {
// type: "articles",
// id: "0",
// attributes: [Object],
// relationships: [Object],
// },
// {
// type: "articles",
// id: "1",
// attributes: [Object],
// relationships: [Object],
// },
// {
// type: "articles",
// id: "2",
// attributes: [Object],
// relationships: [Object],
// },
// {
// type: "articles",
// id: "3",
// attributes: [Object],
// relationships: [Object],
// },
// {
// type: "articles",
// id: "4",
// attributes: [Object],
// relationships: [Object],
// },
// ],
// data: {
// type: "users",
// id: "0",
// attributes: {
// createdAt: "2020-05-22T17:27:53.838Z",
// articles: [Array],
// comments: [Array],
// },
// relationships: { articles: [Object] },
// },
// }
})();