Stackedit/src/services/userSvc.js

80 lines
2.0 KiB
JavaScript
Raw Normal View History

2017-11-15 08:12:56 +00:00
import store from '../store';
2018-09-19 08:59:22 +00:00
const infoPromisesByUserId = {};
const infoResolversByType = {};
const subPrefixesByType = {};
const typesBySubPrefix = {};
2017-11-15 08:12:56 +00:00
2018-05-04 18:07:28 +00:00
const parseUserId = (userId) => {
const prefix = userId[2] === ':' && userId.slice(0, 2);
2018-09-19 08:59:22 +00:00
const type = typesBySubPrefix[prefix];
2018-05-04 18:07:28 +00:00
return type ? [type, userId.slice(3)] : ['google', userId];
};
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;
}
const loginType = store.getters['workspace/loginToken'];
const prefix = subPrefixesByType[loginType];
return prefix ? `${prefix}:${loginToken.sub}` : loginToken.sub;
},
addInfo(info) {
infoPromisesByUserId[info.id] = Promise.resolve(info);
store.commit('userInfo/addItem', info);
2018-04-27 14:37:05 +00:00
},
2018-05-13 13:27:33 +00:00
async getInfo(userId) {
2018-09-19 08:59:22 +00:00
if (!userId) {
return {};
}
2018-05-04 18:07:28 +00:00
2018-09-19 08:59:22 +00:00
let infoPromise = infoPromisesByUserId[userId];
if (infoPromise) {
return infoPromise;
}
2017-11-15 08:12:56 +00:00
2018-09-19 08:59:22 +00:00
const [type, sub] = parseUserId(userId);
// Try to find a token with this sub to resolve name as soon as possible
const token = store.getters[`data/${type}TokensBySub`][sub];
if (token) {
store.commit('userInfo/addItem', {
id: userId,
name: token.name,
});
}
if (store.state.offline) {
return {};
}
// Get user info from helper
infoPromise = new Promise(async (resolve) => {
const infoResolver = infoResolversByType[type];
if (infoResolver) {
try {
const userInfo = await infoResolver(sub);
this.addInfo(userInfo);
resolve(userInfo);
} catch (err) {
if (err && err.message === 'RETRY') {
infoPromisesByUserId[userId] = null;
2018-07-17 19:58:40 +00:00
}
2018-09-19 08:59:22 +00:00
resolve({});
2018-05-04 18:07:28 +00:00
}
2017-11-15 08:12:56 +00:00
}
2018-09-19 08:59:22 +00:00
});
infoPromisesByUserId[userId] = infoPromise;
return infoPromise;
2017-11-15 08:12:56 +00:00
},
};