devour-js / devour-client

Don't just consume your JSON API, Devour it...
https://www.npmjs.com/package/devour-client
ISC License
429 stars 89 forks source link

Cannot seem to be able to replace errors middleware #117

Closed danherd closed 6 years ago

danherd commented 6 years ago

Here's the relevant code:

store/utils/json-api.js

import JsonApi from 'devour-client'

var js = new JsonApi({
  apiUrl: process.env.API_URL
})

js.insertMiddlewareBefore('axios-request', {
  name: 'set-loading',
  req: (payload) => {
    window.app.$root.isLoading = true
    return payload
  }
})

js.insertMiddlewareAfter('response', {
  name: 'unset-loading',
  req: (payload) => {
    window.app.$root.isLoading = false
    return payload
  }
})

js.replaceMiddleware('errors', {
  name: 'replace-error-middleware',
  error: (payload) => {
    console.log(payload)
    return payload
  }
})

export const jsonApi = js

store/modules/user.js (truncated)

import { jsonApi } from '@/store/utils/json-api'
...
  actions: {
    login (store, payload) {
      jsonApi.create('login', { test: 'test' }, {}, payload)
      .then(response => {
        ...
      })
      .catch(error => {
        console.log(error)
      })
...

As the API call returns an error, I would expect to see the payload in the console, but instead I get the 'TypeError: Cannot read property 'pointer' of undefined' from line 46 of res-errors.js, leading me to believe the call to 'js.replaceMiddleware' in the first file is not actually doing anything. The weird thing is, the calls to 'js.insertMiddlewareBefore' and 'js.insertMiddlewareAfter' work fine.

So, is this a bug, or am I doing something wrong?

danherd commented 6 years ago

Hmm. It would seem 'resetMiddleware' basically wipes every middleware change you've made. How can I add a middleware for a particular action, them remove it immediately afterwards?

danherd commented 6 years ago

Ignore this. I now know more about how the middleware works!