Stackedit/src/services/userSvc.js

60 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 });
},
2017-11-15 08:12:56 +00:00
getInfo(userId) {
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-05-04 18:07:28 +00:00
const token = store.getters[`data/${type}Tokens`][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) {
case 'github': {
return githubHelper.getUser(sub)
.catch((err) => {
if (err.status !== 404) {
promised[userId] = false;
}
});
}
case 'google':
default: {
return googleHelper.getUser(sub)
.catch((err) => {
if (err.status !== 404) {
promised[userId] = false;
}
});
}
}
2017-11-15 08:12:56 +00:00
}
}
2018-05-04 18:07:28 +00:00
return null;
2017-11-15 08:12:56 +00:00
},
};