diff --git a/src/store/index.js b/src/store/index.js index 709839439d..1b668279d9 100755 --- a/src/store/index.js +++ b/src/store/index.js @@ -95,6 +95,9 @@ const plugins = [ }) // populate cache } if (mutation.type.indexOf(types.SN_USER) === 0) { // check if this mutation is cart related + global.db.usersCollection.setItem('current-user', store.user.current).catch((reason) => { + console.error(reason) // it doesn't work on SSR + }) // populate cache global.db.usersCollection.setItem('current-token', store.user.token).catch((reason) => { console.error(reason) // it doesn't work on SSR }) // populate cache diff --git a/src/store/modules/user.js b/src/store/modules/user.js index 2c0e1d4b60..8570e0ed99 100644 --- a/src/store/modules/user.js +++ b/src/store/modules/user.js @@ -3,7 +3,8 @@ import config from '../../config.json' // initial state const state = { - token: '' + token: '', + current: null } const getters = { @@ -11,6 +12,10 @@ const getters = { // actions const actions = { + + /** + * Login user and return user profile and current token + */ login (context, { username, password }) { return fetch(config.users.endpoint + '/login', { method: 'POST', mode: 'cors', @@ -33,20 +38,51 @@ const actions = { }) }, - me (context) { - console.log(config.users.endpoint + '/me?token=' + context.state.token) - return fetch(config.users.endpoint + '/me?token=' + context.state.token, { method: 'GET', - mode: 'cors', - headers: { - 'Accept': 'application/json, text/plain, */*', - 'Content-Type': 'application/json' - } - }).then(resp => { return resp.json() }) - .then((resp) => { - if (resp.code === 200) { - context.commit(types.USER_INFO_LOADED, resp.result) + /** + * Load current user profile + */ + me (context, { refresh = true }) { + return new Promise((resolve, reject) => { + const cache = global.db.usersCollection + let resolvedFromCache = false + cache.getItem('current-user', (err, res) => { + if (err) { + console.error(err) + return + } + + if (res) { + context.commit(types.USER_INFO_LOADED, res) + + resolve(res) + resolvedFromCache = true + console.log('Current user served from cache') + } + }) + + if (refresh) { + console.log(config.users.endpoint + '/me?token=' + context.state.token) + return fetch(config.users.endpoint + '/me?token=' + context.state.token, { method: 'GET', + mode: 'cors', + headers: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': 'application/json' + } + }).then(resp => { return resp.json() }) + .then((resp) => { + if (resp.code === 200) { + context.commit(types.USER_INFO_LOADED, resp.result) // this also stores the current user to localForage + } + if (!resolvedFromCache) { + resolve(resp.code === 200 ? resp : null) + } + return resp + }) + } else { + if (!resolvedFromCache) { + resolve(null) + } } - return resp }) } }