Permalink
Browse files

feat: refactor init logic to $auth.init and improve error handling

resetOnError set to `false` by default
  • Loading branch information...
pi0 committed Feb 4, 2018
1 parent 87027ad commit b58ca173e75b6084b767bb5aeeb7cba47b21b79c
Showing with 20 additions and 15 deletions.
  1. +2 −2 README.md
  2. +1 −1 lib/defaults.js
  3. +13 −5 lib/templates/auth.class.js
  4. +4 −7 lib/templates/auth.plugin.js
@@ -118,7 +118,7 @@ Listen for auth errors: (`plugins/auth.js`)
```js
export default function({ $auth }) {
$auth.onError(({ name, error }) => {
$auth.onError((error, name, endpoint) => {
console.error(name, error)
})
}
@@ -250,7 +250,7 @@ If enabled, user will be auto fetched after login.
### `resetOnError`
* Default: `true`
* Default: `false`
If enabled, user will be automatically logged out if any error happens. (For example when token expired)
@@ -1,6 +1,6 @@
module.exports = {
fetchUserOnLogin: true,
resetOnError: true,
resetOnError: false,
rewriteRedirects: true,
watchLoggedIn: true,
namespace: 'auth',
@@ -11,7 +11,9 @@ export default class Auth {
this.ctx = ctx
this.app = ctx.app
this.options = options
}
init () {
// Error listeners
this._errorListeners = []
@@ -30,6 +32,12 @@ export default class Auth {
if (this.options.watchLoggedIn && process.browser) {
this._watchLoggedIn()
}
// Sync token
this.syncToken()
// Fetch user if is not available
return this.state.user ? Promise.resolve() : this.fetchUser()
}
_registerVuexStore () {
@@ -203,12 +211,12 @@ export default class Auth {
try {
const { data } = await this.$axios.request(opts)
return opts.propertyName ? getProp(data, opts.propertyName) : data
} catch (err) {
this._onError({ name, err, endpoint })
} catch (error) {
// Call all error handlers
this._onError(error, name, endpoint)
if (process.browser) {
throw err
}
// Throw error
throw error
}
}
@@ -14,11 +14,8 @@ export default function (ctx, inject) {
// Inject it to nuxt context as $auth
inject('auth', $auth)
// Sync token
$auth.syncToken()
// Fetch user if is not available
if (!$auth.state.user) {
return $auth.fetchUser()
}
// Initialize auth
return $auth
.init()
.catch(process.server ? () => { } : console.error)
}

0 comments on commit b58ca17

Please sign in to comment.