Last active
April 15, 2020 07:47
-
-
Save spacemeowx2/26d42681c7f5ea20d66eda2dc3dfc4f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function gqlPing(server, delay = 0) { | |
return new Promise((res, rej) => { | |
const ws = new WebSocket(`ws://${server}`, 'graphql-ws') | |
let timeoutId = undefined | |
let lastTime = undefined; | |
const doPing = () => { | |
ws.send(`{"id":"1","type":"start","payload":{"variables":{},"extensions":{},"operationName":null,"query":"subscription{serverInfo{online}}"}}`) | |
lastTime = Date.now() | |
} | |
ws.onmessage = (e) => { | |
const data = JSON.parse(e.data) | |
if (data.type === 'data' && data.id === '1') { | |
let delta = Date.now() - lastTime | |
res(delta) | |
ws.send(`{"id":"1","type":"stop"}`) | |
ws.close() | |
} | |
} | |
ws.onclose = () => { | |
timeoutId && clearTimeout(timeoutId) | |
} | |
ws.onerror = (e) => { | |
rej(e) | |
} | |
ws.onopen = () => { | |
ws.send(`{"type":"connection_init","payload":{}}`) | |
timeoutId = setTimeout(doPing, delay) | |
} | |
}) | |
} | |
// example: gqlPing('localhost:11451').then((ms) => console.log(ms)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment