forked from iohzrd/follow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-pubsub.js
57 lines (55 loc) · 1.76 KB
/
test-pubsub.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
const fs = require("fs-extra");
const IpfsHttpClient = require("ipfs-http-client");
const ipfs = IpfsHttpClient();
const handleComment = msg => {
console.log("New comment...");
// open file...
const filePath = "comments.json";
if (!fs.existsSync(filePath)) {
const initObj = { comments: [] };
fs.writeFileSync(filePath, JSON.stringify(initObj));
}
const raw = fs.readFileSync(filePath);
const commentsFile = JSON.parse(raw);
try {
const comment = JSON.parse(msg.data);
// TODO: ID blacklist...
// TODO: global cooldown...
// TODO: per "from" cooldown...
// validate fields...
if (
typeof comment === "object" &&
typeof comment.ts === "number" &&
typeof comment.msg === "string" &&
comment.msg.length > 0
) {
// loose time validation...
// exlcude messages that are more than a 1m different from now
const delta = Math.abs(comment.ts - Math.floor(new Date().getTime()));
if (delta < 60 * 1000) {
comment.from = msg.from;
// filter duplicates
if (
!commentsFile.comments.some(
existingComment =>
existingComment.msg === comment.msg &&
existingComment.from === comment.from
)
) {
console.log(comment);
commentsFile.comments.push(comment);
fs.writeFileSync(filePath, JSON.stringify(commentsFile));
}
}
}
} catch (error) {
console.log(error);
}
};
async function main(topic, msg) {
const ts = Math.floor(new Date().getTime());
const msgObj = { ts: ts, msg: msg };
await ipfs.pubsub.publish(topic, JSON.stringify(msgObj));
await ipfs.pubsub.subscribe(topic, handleComment);
}
main("QmUsHMBjzxGMJy19d9XUNHKRQ21eUNsRAdAa8VMrJbQowJ", "bishasdkfhaiod");