From b58ca173e75b6084b767bb5aeeb7cba47b21b79c Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sun, 4 Feb 2018 12:31:27 +0330 Subject: [PATCH] feat: refactor init logic to $auth.init and improve error handling resetOnError set to `false` by default --- README.md | 4 ++-- lib/defaults.js | 2 +- lib/templates/auth.class.js | 18 +++++++++++++----- lib/templates/auth.plugin.js | 11 ++++------- 4 files changed, 20 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 64ca0b4ca..f10ecab36 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/lib/defaults.js b/lib/defaults.js index b02924b5e..a1b0368cf 100644 --- a/lib/defaults.js +++ b/lib/defaults.js @@ -1,6 +1,6 @@ module.exports = { fetchUserOnLogin: true, - resetOnError: true, + resetOnError: false, rewriteRedirects: true, watchLoggedIn: true, namespace: 'auth', diff --git a/lib/templates/auth.class.js b/lib/templates/auth.class.js index 510ac6166..b9e324774 100644 --- a/lib/templates/auth.class.js +++ b/lib/templates/auth.class.js @@ -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 } } diff --git a/lib/templates/auth.plugin.js b/lib/templates/auth.plugin.js index 480fb6e6f..82ebb105b 100644 --- a/lib/templates/auth.plugin.js +++ b/lib/templates/auth.plugin.js @@ -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) }