From 151868aac70199542ed8fb2e9552f4e29daed2de Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 2 Feb 2018 01:10:04 +0330 Subject: [PATCH] feat: $auth.onError --- lib/auth.js | 32 +++++++++++++++++++++----------- package.json | 1 - test/fixture/pages/index.vue | 10 ++-------- yarn.lock | 10 ---------- 4 files changed, 23 insertions(+), 30 deletions(-) diff --git a/lib/auth.js b/lib/auth.js index c2280c25b..1d0119fb8 100644 --- a/lib/auth.js +++ b/lib/auth.js @@ -1,16 +1,16 @@ import Cookie from 'cookie' import Cookies from 'js-cookie' import Vue from 'vue' -import Hookable from 'hable' -export default class Auth extends Hookable { +export default class Auth { constructor (ctx, options) { - super() - this.ctx = ctx this.app = ctx.app this.options = options + // Error listeners + this._errorListeners = [] + // Keep token out of the store for security reasons Vue.set(this, 'token', null) @@ -42,7 +42,7 @@ export default class Auth extends Hookable { } _resetOnError () { - this.hook('error', () => { + this.onError(() => { this.reset() }) } @@ -60,6 +60,16 @@ export default class Auth extends Hookable { ) } + onError (listener) { + this._errorListeners.push(listener) + } + + _onError () { + for (let fn of this._errorListeners) { + fn.apply(this, arguments) + } + } + get $axios () { if (!this.app.$axios) { throw new Error('$axios is not available') @@ -174,7 +184,7 @@ export default class Auth extends Hookable { return cookies[name] } - async _fetch (name, endpoint) { + async _request (name, endpoint) { const defaults = this.options.endpoints[name] if (!defaults) { return @@ -185,13 +195,13 @@ export default class Auth extends Hookable { Object.assign({}, defaults, endpoint) ) return data - } catch (error) { - await this.callHook('error', { name, endpoint, error }) + } catch (err) { + this._onError({ name, err, endpoint }) } } async login (endpoint) { - const data = await this._fetch('login', endpoint) + const data = await this._request('login', endpoint) if (!data) { return } @@ -213,7 +223,7 @@ export default class Auth extends Hookable { return } - const data = await this._fetch('user', endpoint) + const data = await this._request('user', endpoint) if (!data) { return } @@ -223,7 +233,7 @@ export default class Auth extends Hookable { } async logout (endpoint) { - await this._fetch('logout', endpoint) + await this._request('logout', endpoint) this.reset() } diff --git a/package.json b/package.json index ce2646b7f..0245d763c 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,6 @@ "dependencies": { "@nuxtjs/axios": "^5.0.0-rc.2", "cookie": "^0.3.1", - "hable": "^0.0.7", "js-cookie": "^2.2.0", "lodash": "^4.17.4" }, diff --git a/test/fixture/pages/index.vue b/test/fixture/pages/index.vue index 14ee85b11..2b693e68f 100644 --- a/test/fixture/pages/index.vue +++ b/test/fixture/pages/index.vue @@ -13,16 +13,10 @@