diff options
| author | schneefux <schneefux+commit@schneefux.xyz> | 2017-04-11 21:21:22 +0200 |
|---|---|---|
| committer | schneefux <schneefux+commit@schneefux.xyz> | 2017-04-11 21:21:22 +0200 |
| commit | 0564241327ecc6eb08cd716f510ebb0afbb3eeb3 (patch) | |
| tree | e27842bd96099e54fadb0a1018d9ff266acd3465 /api.js | |
| parent | 291cf5046f1497c49b0266d0d818882a2b96d5d4 (diff) | |
| download | discordbot-0564241327ecc6eb08cd716f510ebb0afbb3eeb3.tar.gz discordbot-0564241327ecc6eb08cd716f510ebb0afbb3eeb3.zip | |
draft: rewrite in node
Diffstat (limited to 'api.js')
| -rw-r--r-- | api.js | 73 |
1 files changed, 73 insertions, 0 deletions
@@ -0,0 +1,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 }; +} |
