58 lines
1.6 KiB
JavaScript
58 lines
1.6 KiB
JavaScript
window.BackOneContacts = (function () {
|
|
let cache = null;
|
|
|
|
async function load() {
|
|
if (cache) return cache;
|
|
try {
|
|
const res = await BackOneAuth.fetchWithAuth('/api/backone/contacts', { cache: 'no-store' })
|
|
.catch(() => BackOneAuth.fetchWithAuth('/app/api/contacts', { cache: 'no-store' }));
|
|
if (!res.ok) {
|
|
cache = {};
|
|
return cache;
|
|
}
|
|
cache = await res.json();
|
|
if (!cache || typeof cache !== 'object') cache = {};
|
|
} catch (_) {
|
|
cache = {};
|
|
}
|
|
return cache;
|
|
}
|
|
|
|
function getDisplayName(peerId, controllerName) {
|
|
const c = cache || {};
|
|
const entry = c[peerId];
|
|
if (entry && entry.nickname) return entry.nickname;
|
|
if (controllerName) return controllerName;
|
|
return peerId;
|
|
}
|
|
|
|
function getNickname(peerId) {
|
|
const entry = (cache || {})[peerId];
|
|
return entry && entry.nickname ? entry.nickname : '';
|
|
}
|
|
|
|
async function setNickname(peerId, nickname) {
|
|
await load();
|
|
const patch = {};
|
|
patch[peerId] = { nickname: nickname || '' };
|
|
const res = await BackOneAuth.fetchWithAuth('/api/backone/contacts', {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(patch)
|
|
}).catch(() => BackOneAuth.fetchWithAuth('/app/api/contacts', {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(patch)
|
|
}));
|
|
if (!res.ok) throw new Error('Failed to save nickname');
|
|
cache = await res.json();
|
|
return cache;
|
|
}
|
|
|
|
function invalidate() {
|
|
cache = null;
|
|
}
|
|
|
|
return { load, getDisplayName, getNickname, setNickname, invalidate };
|
|
})();
|