From 0564241327ecc6eb08cd716f510ebb0afbb3eeb3 Mon Sep 17 00:00:00 2001 From: schneefux Date: Tue, 11 Apr 2017 21:21:22 +0200 Subject: draft: rewrite in node --- api.js | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 api.js (limited to 'api.js') diff --git a/api.js b/api.js new file mode 100644 index 0000000..fef1ffe --- /dev/null +++ b/api.js @@ -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 }; +} -- cgit v1.3.1