Skip to content

Instantly share code, notes, and snippets.

@58bits
Created December 12, 2016 10:42
Show Gist options
  • Select an option

  • Save 58bits/c7b7dccf3f922fde13275d1a54990838 to your computer and use it in GitHub Desktop.

Select an option

Save 58bits/c7b7dccf3f922fde13275d1a54990838 to your computer and use it in GitHub Desktop.

Revisions

  1. Anthony Bouch created this gist Dec 12, 2016.
    63 changes: 63 additions & 0 deletions interceptors.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    import { isArray } from 'lodash'
    import { decode, encode } from 'querystring'

    const DEBUG = true
    const DEBUG_SESSION = 10942

    export default (http, store, router) => {
    // Add a request interceptor
    http.interceptors.request.use((config) => {
    // PhpStorm needs to be started first, and a debug session
    // initiated there. The DEBUG_SESSION value able will also
    // need to be updated to match the session identifier.
    if (DEBUG) {
    let components = config.url.split('?')
    let qs = {}
    if (components[1]) {
    qs = decode(components[1])
    }
    qs.XDEBUG_SESSION_START = DEBUG_SESSION
    config.url = `${components[0]}?${encode(qs)}`
    }
    return config
    }, (error) => {
    // Do something with request error
    return Promise.reject(error)
    })

    // https://github.com/mzabriskie/axios#interceptors
    // Add a response interceptor
    http.interceptors.response.use((response) => {
    return response
    }, (error) => {
    /**
    * This is a central point to handle all
    * error messages generated by HTTP
    * requests
    */
    const { response } = error
    /**
    * If token is either expired, not provided or invalid
    * then redirect to login. On server side the error
    * messages can be changed on app/Providers/EventServiceProvider.php
    */
    if ([401, 400].indexOf(response.status) > -1) {
    router.push({ name: 'login.index' })
    }
    /**
    * Error messages are sent in arrays
    */
    if (isArray(response.data)) {
    store.dispatch('setMessage', { type: 'error', message: response.data.messages })
    /**
    * Laravel generated validation errors are
    * sent in an object
    */
    } else {
    store.dispatch('setMessage', { type: 'validation', message: response.data })
    }

    store.dispatch('setFetching', { fetching: false })
    return Promise.reject(error)
    })
    }