api.js
971 Bytes
/**
* 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]
*/
export async function api(method, path, body) {
const token = getToken()
const response = await fetch(path, {
method,
headers: {
...(body === undefined ? {} : { 'content-type': 'application/json' }),
...(token === null ? {} : { authorization: `Bearer ${token}` }),
},
body: body === undefined ? undefined : JSON.stringify(body),
})
const json = await response.json()
if (!response.ok) throw new Error(json.error.message)
return json
}