Skip to content

Commit b58ca17

Browse files
author
Pooya Parsa
committed
feat: refactor init logic to $auth.init and improve error handling
resetOnError set to `false` by default
1 parent 87027ad commit b58ca17

4 files changed

Lines changed: 20 additions & 15 deletions

File tree

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ Listen for auth errors: (`plugins/auth.js`)
118118
119119
```js
120120
export default function({ $auth }) {
121-
$auth.onError(({ name, error }) => {
121+
$auth.onError((error, name, endpoint) => {
122122
console.error(name, error)
123123
})
124124
}
@@ -250,7 +250,7 @@ If enabled, user will be auto fetched after login.
250250
251251
### `resetOnError`
252252
253-
* Default: `true`
253+
* Default: `false`
254254
255255
If enabled, user will be automatically logged out if any error happens. (For example when token expired)
256256

lib/defaults.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
module.exports = {
22
fetchUserOnLogin: true,
3-
resetOnError: true,
3+
resetOnError: false,
44
rewriteRedirects: true,
55
watchLoggedIn: true,
66
namespace: 'auth',

lib/templates/auth.class.js

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ export default class Auth {
1111
this.ctx = ctx
1212
this.app = ctx.app
1313
this.options = options
14+
}
1415

16+
init () {
1517
// Error listeners
1618
this._errorListeners = []
1719

@@ -30,6 +32,12 @@ export default class Auth {
3032
if (this.options.watchLoggedIn && process.browser) {
3133
this._watchLoggedIn()
3234
}
35+
36+
// Sync token
37+
this.syncToken()
38+
39+
// Fetch user if is not available
40+
return this.state.user ? Promise.resolve() : this.fetchUser()
3341
}
3442

3543
_registerVuexStore () {
@@ -203,12 +211,12 @@ export default class Auth {
203211
try {
204212
const { data } = await this.$axios.request(opts)
205213
return opts.propertyName ? getProp(data, opts.propertyName) : data
206-
} catch (err) {
207-
this._onError({ name, err, endpoint })
214+
} catch (error) {
215+
// Call all error handlers
216+
this._onError(error, name, endpoint)
208217

209-
if (process.browser) {
210-
throw err
211-
}
218+
// Throw error
219+
throw error
212220
}
213221
}
214222

lib/templates/auth.plugin.js

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,8 @@ export default function (ctx, inject) {
1414
// Inject it to nuxt context as $auth
1515
inject('auth', $auth)
1616

17-
// Sync token
18-
$auth.syncToken()
19-
20-
// Fetch user if is not available
21-
if (!$auth.state.user) {
22-
return $auth.fetchUser()
23-
}
17+
// Initialize auth
18+
return $auth
19+
.init()
20+
.catch(process.server ? () => { } : console.error)
2421
}

0 commit comments

Comments
 (0)