Skip to content

Connection

Jacob Bergholtz edited this page Aug 30, 2023 · 6 revisions

Connection

Connection is an abstraction on top of Hexgate & LcuClient. It quietly handles authentication and connection with the Lcu.

Event Summary

onStatusChange

import { Connection } from 'hexgate'

const client = new Connection({
  onStatusChange(status, prev) {
    client.logger.info({ status }, 'client status changed')
  } 
})

client.connect()

onConnect

Once the websocket is ready, onConnect is called with your SafeConnection<Logger, Recipe> guaranteeing NonNullable access to https, ws, & recipe.

new Connection({
  async onConnect(con) {
    con.ws.subscribe('OnJsonApiEvent_lol-champ-select_v1_session', handleChampSelect)
    con.logger.info("Connected to the lcu!")
  }
}).connect()

onDisconnect

When the websocket is closed, onDisconnect is called with your UnsafeConnection<Logger, Recipe>, guaranteeing null access to https, ws, & recipe.

The default behavior is to do nothing when the League of Legends client shuts down.

new Connection({
  async onDisconnect(discon) {
    // Wait for LoL to restart
    await sleep(4000)
    // Reconnect
    discon.connect()
  }
}).connect()

Recipe Usage

Pass a RecipeFn returned by createRecipe or define a createRecipe method in your config. You may use either one, or none, but not both.

method option

import { Connection } from 'hexgate'

const client = new Connection({
  createRecipe({ build, wrap, unwrap }) {
    const to = unwrap('should never error!') // extracts data
    return {
      getCurrentSummoner: wrap(build('/lol-summoner/v1/current-summoner').method('get').create())({
        to
      })
    }
  },
  async onConnect(con) {
    const summoner = await con.recipe.getCurrentSummoner()
    con.logger.info(summoner, `Welcome, ${summoner.displayName}`)
  },
})

client.connect()

import option

import { Connection, createRecipe } from 'hexgate'

const recipe = createRecipe(({ build, wrap, unwrap }) => {
  const to = unwrap('should never error!')
  return {
    getCurrentSummoner: wrap(build('/lol-summoner/v1/current-summoner').method('get').create())({
      to
    })
  }
})

const client = new Connection({
  recipe,
  async onConnect(con) {
    const summoner = await con.recipe.getCurrentSummoner()
    con.logger.info(summoner, `Welcome, ${summoner.displayName}`)
  },
})

client.connect()

Additional Options

logger

Use any logger that extends BaseLogger. I would recommend pino.

Defaults to built-in console.

interval

The interval between authentication attempts. Once the websocket is open, polling is no longer used.

Defaults to 1500 ms.