Stackedit/src/services/userSvc.js

92 lines
2.6 KiB
JavaScript
Raw Normal View History

2017-11-15 08:12:56 +00:00
import store from '../store';
import utils from './utils';
const refreshUserInfoAfter = 60 * 60 * 1000; // 60 minutes
2017-11-15 08:12:56 +00:00
2018-09-19 08:59:22 +00:00
const infoResolversByType = {};
const subPrefixesByType = {};
const typesBySubPrefix = {};
2017-11-15 08:12:56 +00:00
const lastInfosByUserId = {};
const infoPromisedByUserId = {};
const sanitizeUserId = (userId) => {
2018-05-04 18:07:28 +00:00
const prefix = userId[2] === ':' && userId.slice(0, 2);
if (typesBySubPrefix[prefix]) {
return userId;
}
return `go:${userId}`;
2018-05-04 18:07:28 +00:00
};
const parseUserId = userId => [typesBySubPrefix[userId.slice(0, 2)], userId.slice(3)];
const refreshUserInfos = () => {
if (store.state.offline) {
return;
}
Object.entries(lastInfosByUserId)
.filter(([userId, lastInfo]) => lastInfo === 0 && !infoPromisedByUserId[userId])
.forEach(async ([userId]) => {
const [type, sub] = parseUserId(userId);
const infoResolver = infoResolversByType[type];
if (infoResolver) {
try {
infoPromisedByUserId[userId] = true;
const userInfo = await infoResolver(sub);
store.commit('userInfo/setItem', userInfo);
} finally {
infoPromisedByUserId[userId] = false;
lastInfosByUserId[userId] = Date.now();
}
}
});
};
2018-09-19 08:59:22 +00:00
2017-11-15 08:12:56 +00:00
export default {
2018-09-19 08:59:22 +00:00
setInfoResolver(type, subPrefix, resolver) {
infoResolversByType[type] = resolver;
subPrefixesByType[type] = subPrefix;
typesBySubPrefix[subPrefix] = type;
},
getCurrentUserId() {
const loginToken = store.getters['workspace/loginToken'];
if (!loginToken) {
return null;
}
2018-09-20 09:00:07 +00:00
const loginType = store.getters['workspace/loginType'];
2018-09-19 08:59:22 +00:00
const prefix = subPrefixesByType[loginType];
return prefix ? `${prefix}:${loginToken.sub}` : loginToken.sub;
},
sanitizeUserId,
addUserInfo(userInfo) {
store.commit('userInfo/setItem', userInfo);
lastInfosByUserId[userInfo.id] = Date.now();
2018-04-27 14:37:05 +00:00
},
addUserId(userId) {
if (userId) {
const sanitizedUserId = sanitizeUserId(userId);
const lastInfo = lastInfosByUserId[sanitizedUserId];
if (lastInfo === undefined) {
// Try to find a token with this sub to resolve name as soon as possible
const [type, sub] = parseUserId(sanitizedUserId);
const token = store.getters['data/tokensByType'][type][sub];
if (token) {
store.commit('userInfo/setItem', {
id: sanitizedUserId,
name: token.name,
});
2018-05-04 18:07:28 +00:00
}
2017-11-15 08:12:56 +00:00
}
2018-09-19 08:59:22 +00:00
if (lastInfo === undefined || lastInfo + refreshUserInfoAfter < Date.now()) {
lastInfosByUserId[sanitizedUserId] = 0;
refreshUserInfos();
}
}
2017-11-15 08:12:56 +00:00
},
};
// Get user info periodically
utils.setInterval(() => refreshUserInfos(), 60 * 1000);