forked from ivansglazunov/research-orientdb-peer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
101 lines (90 loc) · 2.52 KB
/
index.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
90
91
92
93
94
95
96
97
98
99
100
101
import gql from 'graphql-tag';
import graphql from 'graphql-anywhere';
import * as _ from 'lodash';
import { Query, find } from 'mingo';
import { Cursor } from 'ancient-cursor/lib/cursor';
import { Peer } from 'ancient-peer/lib/peer';
import channel from 'ancient-channels/lib/channel';
const users = new Cursor().exec(null, []);
const posts = new Cursor().exec(null, []);
users.apply({
type: 'set',
path: '0',
value: { id: 1, name: 'a', age: 17 },
});
users.apply({
type: 'set',
path: '1',
value: { id: 2, name: 'b', age: 21 },
});
posts.apply({
type: 'set',
path: '0',
value: { id: 1, author: 1, content: 'aaa' },
});
const resolver = (fieldName, root) => {
if (root._type == 'cursors') {
if (fieldName == 'users') {
return _.map(find(users.data, {}).sort({ id: 1 }).all(), d => _.extend({ _type: 'user' }, d));
}
if (fieldName == 'posts') {
return _.map(find(posts.data, {}).sort({ id: 1 }).all(), d => _.extend({ _type: 'post' }, d));
}
} else if (root._type == 'user') {
if (fieldName == 'posts') {
return _.map(find(posts.data, { author: root.id }).sort({ id: 1 }).all(), d => _.extend({ _type: 'post' }, d));
}
return root[fieldName];
} else if (root._type == 'post') {
if (fieldName == 'author') {
return _.map(find(users.data, { id: root.author }).sort({ id: 1 }).all(), d => _.extend({ _type: 'user' }, d));
}
return root[fieldName];
}
};
class AppPeer extends Peer {
getApiCallbacks(apiQuery, callback) {
callback((() => {
const cursors = [];
return {
gotQuery: (channelId, { cursorId, query, queryId }) => {
cursors.push({ cursorId, channelId });
const value = graphql(
resolver,
gql`${query}`, {
_type: 'cursors',
users,
posts,
},
);
this.sendBundles(channelId, {
type: 'set',
path: '',
value,
cursorId,
});
},
cursorDestroyed: (channelId, cursorId) => {
_.remove(cursors, (c: any) => c.cursorId == cursorId && c.channelId == channelId);
},
channelDestroyed: (channelId) => {
_.remove(cursors, (c: any) => c.channelId == channelId);
},
}
})());
}
}
const peer = new AppPeer();
const channelId = peer.connect(peer);
const cursor = peer.exec(channelId, null, `{
users {
name
posts {
content
author {
name
}
}
}
}`);
console.log(JSON.stringify(cursor.data));