api.js 1.15 KB
/**
 * voko-server 网页接口的唯一调用点。access token 存在 sessionStorage(Alpha 内部使用)。
 */

const TOKEN_KEY = 'voko.access_token'

export function getToken() {
  return sessionStorage.getItem(TOKEN_KEY)
}

/** @param {string|null} token */
export function setToken(token) {
  if (token === null) sessionStorage.removeItem(TOKEN_KEY)
  else sessionStorage.setItem(TOKEN_KEY, token)
}

/**
 * @param {string} method
 * @param {string} path
 * @param {unknown} [body]
 * @param {string} [idempotencyKey] 写接口的幂等键:同一次提交重试不会重复扣积分
 */
export async function api(method, path, body, idempotencyKey) {
  const token = getToken()
  const response = await fetch(path, {
    method,
    headers: {
      ...(body === undefined ? {} : { 'content-type': 'application/json' }),
      ...(token === null ? {} : { authorization: `Bearer ${token}` }),
      ...(idempotencyKey === undefined ? {} : { 'idempotency-key': idempotencyKey }),
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  })
  const json = await response.json()
  if (!response.ok) throw new Error(json.error.message)
  return json
}