PteroPackages / PteroJS

A verbose API library for Pterodactyl
https://pteropackages.github.io/PteroJS/
MIT License
41 stars 11 forks source link

Big WebSockets refactor #12

Closed chelog closed 2 years ago

chelog commented 2 years ago

There's a result of my thoughts I commented on #11:

Open to any discussions, really prefer if you'd pinged me on Discord instead of comments here :)


Test code:

import { PteroClient, ServerStats } from './PteroJS';

const wait = (delay: number) => new Promise(resolve => setTimeout(resolve, delay))

async function run() {
    const client = new PteroClient('-snip-', '-snip-')
    await client.connect()

    const shard = client.addSocketServer('d7d01832')
    shard.on('serverConnect', socket => console.log(`socket connected for ${shard.id}: ${socket.url}`))
    shard.on('serverDisconnect', () => console.log(`socket disconnected for ${shard.id}`))

    const socket = await shard.connect()

    console.log('listening stats for 3 seconds...')
    const logStats = (stats: ServerStats) => console.log(`${shard.id}'s cpu: ${stats.cpu_absolute}`)
    shard.on('statsUpdate', logStats)
    await wait(3000)
    shard.off('statsUpdate', logStats)

    // dont't forget to reset console colors
    shard.on('serverOutput', (output) => console.log(`${shard.id}'s output: ${output}\x1b[0m`))
    shard.send('send command', ['hello'])

    await shard.disconnect()
    await shard.connect()

    shard.send('send command', ['hello after reconnection'])
}

run()

Result: