-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
70 lines (64 loc) · 1.85 KB
/
client.js
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
var req = require("xhr-request-promise");
var url = "http://localhost";
async function size(topic) {
var got = await req(url+"/size?topic="+topic);
if (got === "fail") {
throw "fail";
} else {
return Number(got);
};
};
async function read(topic, from, to) {
var topic_param = "topic="+topic;
var from_param = from ? "&from="+from : "";
var to_param = to ? "&to="+to : "";
var got = await req(url+"/read?"+topic_param+from_param+to_param);
if (got === "fail") {
throw "fail";
} else {
if (got.length === 0) {
return [];
} else {
var blocks = got.split(";");
var posts = [];
for (var i = 0; i < blocks.length; ++i) {
var time = blocks[i].slice(0, 16);
var author = blocks[i].slice(16, 32);
var message = blocks[i].slice(32, 64);
posts.push({time, author, message});
};
return posts;
};
}
};
async function post(topic, author, message) {
var topic_param = "topic="+topic;
var author_param = "&author="+author;
var message_param = "&message="+message;
var got = await req(url+"/post?"+topic_param+author_param+message_param);
if (got === "fail") {
throw "fail";
} else {
return true;
};
};
async function watch(topic, callback, delay = 1000) {
var size = 0;
setInterval(async () => {
var new_posts = await read(topic, size);
size += new_posts.length;
if (new_posts.length > 0) {
callback(new_posts);
};
}, delay);
};
module.exports = {size, read, post, watch};
//(async () => {
////console.log("read: " + JSON.stringify(await read("0", 30), null, 2));
////console.log("size: " + await size("0"));
////watch("0", (new_posts) => {
////console.log(":: "+new_posts.length+" new_posts:");
////console.log(JSON.stringify(new_posts, null, 2));
////});
////console.log("post: " + await post("0", "4444", "9999"));
//})();