41 lines
1.2 KiB
JavaScript
41 lines
1.2 KiB
JavaScript
function createProgressiveLiveSnapshot({fetchSnapshot}) {
|
|
let value = null;
|
|
let flight = null;
|
|
|
|
const acquire = () => {
|
|
if (value) return Promise.resolve(value);
|
|
if (flight) return flight;
|
|
flight = Promise.resolve().then(() => fetchSnapshot()).then(snapshot => {
|
|
value = snapshot;
|
|
flight = null;
|
|
return snapshot;
|
|
}, error => {
|
|
flight = null;
|
|
throw error;
|
|
});
|
|
return flight;
|
|
};
|
|
|
|
return {
|
|
acquire,
|
|
snapshot:() => value,
|
|
pending:() => flight,
|
|
identity() {
|
|
const user = value?.context?.user || {};
|
|
const login = String(user.login || '').trim();
|
|
return {login, accountKey:login && user.id ? String(user.id) + ':' + login : login};
|
|
},
|
|
};
|
|
}
|
|
|
|
if (typeof window !== 'undefined') {
|
|
window.stackchainProgressiveLiveSnapshot = createProgressiveLiveSnapshot({
|
|
fetchSnapshot:async () => {
|
|
const response = await fetch('api/v1/live', {headers:{Accept:'application/json'}});
|
|
if (!response.ok) throw new Error('HTTP ' + response.status);
|
|
return response.json();
|
|
},
|
|
});
|
|
}
|
|
if (typeof module !== 'undefined' && module.exports) module.exports = createProgressiveLiveSnapshot;
|