-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathdocument-store.ts
105 lines (89 loc) · 2.5 KB
/
document-store.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
102
103
104
105
/**
* An example where:
* - A document store is created storing posts
* - One peer is inserting 1 post
* - Another peer is dialing the first peer and later tries to find all posts
*
*
* If you get confused by the "/// [abc]" lines, they are just meant for the documentation
* website to be able to render parts of the code.
* If you are to copy code from this example, you can safely remove these
*/
/// [imports]
import { field, variant } from "@dao-xyz/borsh";
import { Documents, SearchRequest } from "@peerbit/document";
import { Program } from "@peerbit/program";
import assert from "node:assert";
import { Peerbit } from "peerbit";
import { v4 as uuid } from "uuid";
/// [imports]
/// [client]
const peer = await Peerbit.create();
/// [client]
/// [data]
// This class will store post messages
@variant(0) // version 0
class Post {
@field({ type: "string" })
id: string;
@field({ type: "string" })
message: string;
constructor(message: string) {
this.id = uuid();
this.message = message;
}
}
// This class extends Program which allows it to be replicated amongst peers
@variant("posts")
class PostsDB extends Program {
@field({ type: Documents })
posts: Documents<Post>; // Documents<?> provide document store functionality around your Posts
constructor() {
super();
this.posts = new Documents();
}
/**
* Implement open to control what things are to be done on 'open'
*/
async open(): Promise<void> {
// We need to setup the store in the setup hook
// we can also modify properties of our store here, for example set access control
await this.posts.open({
type: Post,
// You can add more properties here, like
/* canPerform: (entry) => true */
});
}
}
/// [data]
/// [insert]
const store = await peer.open(new PostsDB());
await store.posts.put(new Post("hello world"));
/// [insert]
/// [another-client]
// search for documents from another peer
const peer2 = await Peerbit.create();
// Connect to the first peer
await peer2.dial(peer.getMultiaddrs());
const store2 = await peer2.open<PostsDB>(store.address!);
// Wait for peer1 to be reachable for query
await store.posts.log.waitForReplicator(peer2.identity.publicKey);
const responses: Post[] = await store2.posts.index.search(
new SearchRequest({
query: [], // query all
}),
{
local: true,
remote: true,
},
);
assert.equal(responses.length, 1);
assert.deepEqual(
responses.map((x) => x.message),
["hello world"],
);
/// [another-client]
/// [disconnecting]
await peer.stop();
await peer2.stop();
/// [disconnecting]