Stackedit/src/services/userSvc.js

59 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-11-26 20:58:24 +00:00
import googleHelper from './providers/helpers/googleHelper';
2018-05-04 18:07:28 +00:00
import githubHelper from './providers/helpers/githubHelper';
import utils from './utils';
2017-11-15 08:12:56 +00:00
import store from '../store';
const promised = {};
2018-05-04 18:07:28 +00:00
const parseUserId = (userId) => {
const prefix = userId[2] === ':' && userId.slice(0, 2);
const type = prefix && utils.userIdPrefixes[prefix];
return type ? [type, userId.slice(3)] : ['google', userId];
};
2017-11-15 08:12:56 +00:00
export default {
2018-04-27 14:37:05 +00:00
addInfo({ id, name, imageUrl }) {
promised[id] = true;
store.commit('userInfo/addItem', { id, name, imageUrl });
},
2018-05-13 13:27:33 +00:00
async getInfo(userId) {
2017-11-15 08:12:56 +00:00
if (!promised[userId]) {
2018-05-04 18:07:28 +00:00
const [type, sub] = parseUserId(userId);
2017-11-15 08:12:56 +00:00
// Try to find a token with this sub
2018-06-21 19:16:33 +00:00
const token = store.getters[`data/${type}TokensBySub`][sub];
2017-11-15 08:12:56 +00:00
if (token) {
store.commit('userInfo/addItem', {
id: userId,
name: token.name,
});
}
2018-05-04 18:07:28 +00:00
// Get user info from provider
2017-11-15 08:12:56 +00:00
if (!store.state.offline) {
promised[userId] = true;
2018-05-04 18:07:28 +00:00
switch (type) {
2018-05-13 13:27:33 +00:00
case 'github':
try {
await githubHelper.getUser(sub);
} catch (err) {
if (err.status !== 404) {
promised[userId] = false;
}
}
break;
2018-05-04 18:07:28 +00:00
case 'google':
2018-05-13 13:27:33 +00:00
default:
try {
await googleHelper.getUser(sub);
} catch (err) {
if (err.status !== 404) {
promised[userId] = false;
}
}
2018-05-04 18:07:28 +00:00
}
2017-11-15 08:12:56 +00:00
}
}
},
};