Permalink
Browse files

feat: $auth.onError

  • Loading branch information...
pi0 committed Feb 1, 2018
1 parent d4da740 commit 151868aac70199542ed8fb2e9552f4e29daed2de
Showing with 23 additions and 30 deletions.
  1. +21 −11 lib/auth.js
  2. +0 −1 package.json
  3. +2 −8 test/fixture/pages/index.vue
  4. +0 −10 yarn.lock
@@ -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()
}
@@ -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"
},
@@ -13,16 +13,10 @@
<script>
export default {
data() {
return {
errors: []
}
},
created() {
this.$auth.hook('error', (err => {
this.$auth.onError(err => {
console.error(err)
this.errors.push(err)
}))
})
},
computed: {
state() {

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.

0 comments on commit 151868a

Please sign in to comment.