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
|
#!/usr/bin/node
/* jshint esnext:true */
"use strict";
const request = require("request-promise-native"),
WebSocket = require("ws"),
webstomp = require("webstomp-client"),
Channel = require("async-csp").Channel;
const API_FE_URL = process.env.API_FE_URL || "http://vainsocial.dev/bots/api",
API_WS_URL = process.env.API_WS_URL || "ws://vainsocial.dev/ws",
API_BE_URL = process.env.API_BE_URL || "http://vainsocial.dev/bridge";
const ws = new WebSocket(API_WS_URL, { perMessageDeflate: false }),
notif = webstomp.over(ws);
function connect() {
notif.connect("web", "web",
() => console.log("connected to queue"),
(err) => console.error("error connecting to queue", err));
keepalive();
}
function keepalive() {
ws.ping("", false, true);
setTimeout(this, 60000);
}
ws.on("ready", connect);
// TODO use keepalive / connection pool
async function getFE(url) {
return await request({
uri: API_FE_URL + url,
json: true
});
}
async function postBE(url) {
return await request.post({
uri: API_BE_URL + url,
json: true
});
}
function subscribe(topic, channel) {
notif.subscribe("/topic/" + topic, async (msg) => {
await channel.put(msg.body);
msg.ack();
}, {"ack": "client"});
}
module.exports.searchPlayer = async function (name, timeout=30) {
let channel = new Channel();
subscribe("player." + name, channel);
await postBE("/player/" + name + "/search");
setTimeout(() => channel.close(), timeout*1000);
channel.put(""); // initial fetch
let generator = async () => {
let msg = await channel.take();
if (msg == "search_fail") {
throw "not found";
}
if (msg == Channel.DONE) {
throw "exhausted";
}
return await getFE("/player/" + name);
}
return { next: generator };
}
|