Skip to content

Commit

Permalink
feat: refactor init logic to $auth.init and improve error handling
Browse files Browse the repository at this point in the history
resetOnError set to `false` by default
  • Loading branch information
Pooya Parsa committed Feb 4, 2018
1 parent 87027ad commit b58ca17
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 15 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion lib/defaults.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
fetchUserOnLogin: true,
resetOnError: true,
resetOnError: false,
rewriteRedirects: true,
watchLoggedIn: true,
namespace: 'auth',
Expand Down
18 changes: 13 additions & 5 deletions lib/templates/auth.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ export default class Auth {
this.ctx = ctx
this.app = ctx.app
this.options = options
}

init () {
// Error listeners
this._errorListeners = []

Expand All @@ -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 () {
Expand Down Expand Up @@ -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
}
}

Expand Down
11 changes: 4 additions & 7 deletions lib/templates/auth.plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.