Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
64 changes: 50 additions & 14 deletions src/store/modules/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@ import config from '../../config.json'

// initial state
const state = {
token: ''
token: '',
current: null
}

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',
Expand All @@ -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
})
}
}
Expand Down