OverviewFilesCommitsIssuesDocsReleasesPeers

pgh-legacy / lib / client.js

70 lines · javascript ref:
/**
 * PGH API Client — HTTP client for pear-git JSON API
 *
 * Used by CLI and programmatically.
 */

export class PghClient {
  constructor (opts = {}) {
    this.server = opts.server || 'http://localhost:5005'
    this.token = opts.token || null
  }

  async get (path) {
    const res = await fetch(this.server + path, {
      headers: this._headers()
    })
    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
    return res.json()
  }

  async post (path, body) {
    const res = await fetch(this.server + path, {
      method: 'POST',
      headers: { ...this._headers(), 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    })
    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
    return res.json()
  }

  _headers () {
    const h = { Accept: 'application/json' }
    if (this.token) h.Authorization = `Bearer ${this.token}`
    return h
  }

  async patch (path, body) {
    const res = await fetch(this.server + path, {
      method: 'PATCH',
      headers: { ...this._headers(), 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    })
    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
    return res.json()
  }

  // Convenience methods
  status () { return this.get('/api/status') }
  repos () { return this.get('/api/repos') }
  repo (name) { return this.get(`/api/repos/${name}`) }
  issues (repo, status) { return this.get(`/api/repos/${repo}/issues${status ? '?status=' + status : ''}`) }
  issue (repo, id) { return this.get(`/api/repos/${repo}/issues/${id}`) }
  createIssue (repo, data) { return this.post(`/api/repos/${repo}/issues`, data) }
  updateIssue (repo, id, data) { return this.patch(`/api/repos/${repo}/issues/${id}`, data) }
  comments (repo, id) { return this.get(`/api/repos/${repo}/issues/${id}/comments`) }
  addComment (repo, id, data) { return this.post(`/api/repos/${repo}/issues/${id}/comments`, data) }
  orgs () { return this.get('/api/orgs') }
  users () { return this.get('/api/users') }
  deploy (repo) { return this.post(`/api/deploy/${repo}`, {}) }
  deployStatus () { return this.get('/api/deploy/status') }
  deployConfig (repo) { return this.get(`/api/deploy/config/${repo}`) }
  deployLog (repo) { return this.get(`/api/deploy/log/${repo}`) }
  challenge () { return this.get('/api/auth/challenge') }
  verify (data) { return this.post('/api/auth/verify', data) }
  search (q) { return this.get(`/api/search/code?q=${encodeURIComponent(q)}`) }
  adminStats () { return this.get('/api/admin/stats') }
  adminUsers () { return this.get('/api/admin/users') }
  adminTokens () { return this.get('/api/admin/tokens') }
}