OverviewFilesCommitsIssuesDocsReleasesPeers

hypercore-kb / hyper-social / hyper-social-web / web / js / api.js

87 lines · javascript ref:
/**
 * API client for hyper-social-web backend
 *
 * Uses Identity.authFetch() for authenticated requests.
 * Read endpoints (timeline, accounts list, notifications) work without auth.
 * Write endpoints (post, connect, disconnect) require auth.
 */
const API = {
  // Base path — empty for direct access, or prefix like '/social' behind reverse proxy
  base: (function () {
    const p = window.location.pathname.replace(/\/index\.html$/, '').replace(/\/+$/, '')
    return p || ''
  })(),

  // Authenticated fetch wrapper — uses Identity if available
  async _fetch (url, opts = {}) {
    if (typeof Identity !== 'undefined' && Identity.isReady) {
      return Identity.authFetch(this.base + url, opts)
    }
    return fetch(this.base + url, opts)
  },

  async post (text, targets) {
    const res = await this._fetch('/api/post', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text, targets })
    })
    return res.json()
  },

  async timeline (opts = {}) {
    const params = new URLSearchParams()
    if (opts.source) params.set('source', opts.source)
    if (opts.limit) params.set('limit', opts.limit)
    if (opts.before) params.set('before', opts.before)
    const qs = params.toString()
    const res = await fetch(this.base + '/api/timeline' + (qs ? '?' + qs : ''))
    return res.json()
  },

  async refresh () {
    const res = await fetch(this.base + '/api/feed/refresh')
    return res.json()
  },

  async accounts () {
    const res = await fetch(this.base + '/api/accounts')
    return res.json()
  },

  async connect (data) {
    const res = await this._fetch('/api/accounts/connect', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    return res.json()
  },

  async disconnect (id) {
    const res = await this._fetch('/api/accounts/' + encodeURIComponent(id), {
      method: 'DELETE'
    })
    return res.json()
  },

  async notifications () {
    const res = await fetch(this.base + '/api/notifications')
    return res.json()
  },

  async me () {
    const res = await this._fetch('/api/auth/me')
    return res.json()
  },

  async setUsername (username) {
    const res = await this._fetch('/api/auth/username', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username })
    })
    return res.json()
  }
}