Skip to content

Instantly share code, notes, and snippets.

@spacemeowx2
Last active April 15, 2020 07:47
Show Gist options
  • Save spacemeowx2/26d42681c7f5ea20d66eda2dc3dfc4f4 to your computer and use it in GitHub Desktop.
Save spacemeowx2/26d42681c7f5ea20d66eda2dc3dfc4f4 to your computer and use it in GitHub Desktop.
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