OverviewFilesCommitsIssuesDocsReleasesPeers

keet-tui / lib / client.js

93 lines · javascript ref:
import http from 'bare-http1'

export class KeetClient {
  constructor (opts = {}) {
    this.port = opts.port || 3117
    this.host = opts.host || 'localhost'
  }

  async call (method, params = {}) {
    const result = await this._post('/rpc', { method, params })
    return result
  }

  async rooms () {
    return this._get('/rpc/rooms')
  }

  async messages (roomId, limit = 30) {
    return this._get(`/rpc/messages/${encodeURIComponent(roomId)}?limit=${limit}`)
  }

  async send (roomId, text) {
    return this.call('send', { roomId, text })
  }

  async members (roomId) {
    return this._get(`/rpc/members/${encodeURIComponent(roomId)}`)
  }

  async roomConfig (roomId) {
    return this.call('room.config', { roomId })
  }

  async identity () {
    return this._get('/rpc/identity')
  }

  async status () {
    return this._get('/rpc/status')
  }

  async ping () {
    try {
      const result = await this.status()
      return result.ok === true
    } catch {
      return false
    }
  }

  _get (path) {
    return this._request('GET', path)
  }

  _post (path, body) {
    return this._request('POST', path, body)
  }

  _request (method, urlPath, body) {
    return new Promise((resolve, reject) => {
      const headers = {}
      let payload = null
      if (body) {
        payload = JSON.stringify(body)
        headers['Content-Type'] = 'application/json'
        headers['Content-Length'] = Buffer.byteLength(payload)
      }

      const req = http.request({
        hostname: this.host,
        port: this.port,
        path: urlPath,
        method,
        headers
      }, (res) => {
        let data = ''
        res.on('data', (chunk) => { data += chunk.toString() })
        res.on('end', () => {
          try {
            resolve(JSON.parse(data))
          } catch {
            resolve({ ok: false, error: 'Invalid JSON', raw: data })
          }
        })
      })

      req.on('error', reject)
      if (payload) req.write(payload)
      req.end()
    })
  }
}