Skip to content

Instantly share code, notes, and snippets.

@interjc interjc/ajax.js
Last active Apr 26, 2017

Embed
What would you like to do?
Axios packaging
/**
* import Vuejs
*/
import Vue from 'vue'
/**
* import axios
*
* Usage of Axios
* https://github.com/mzabriskie/axios
*/
import axios from 'axios'
/**
* import toast
*/
import toast from './toast'
/**
* const enviorment variables
* @type {String}
*/
export const BASE = process.env.BASE
export const IS_DEBUG = process.env.IS_DEBUG
export const API_SERIES = process.env.API_SERIES
export const API_VERSION = process.env.API_VERSION
export const API_BASE = IS_DEBUG ? process.env.API_BASE : '/'
export const API_PATH = 'api/'
export const URI_BASE = API_BASE + API_PATH
/**
* axios global configuration
*/
axios.defaults.headers.common['Accept'] = `application/json;${API_SERIES}, version=${API_VERSION}`
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// AUTH_TOKEN
import AuthToken from './authToken'
axios.defaults.headers.common['Authorization'] = AuthToken.get()
/**
* Public definations
*/
let instance = {}
/**
* The ajax class package
*/
class Ajax {
/**
* Creates an instance of Ajax.
*
* @param {Object} [opt={}]
*
* @memberOf Ajax
*/
constructor (opt = {}) {
this.options = Object.assign({
method: 'get',
baseURL: URI_BASE,
params: {},
data: {},
toast: true,
cache: false,
redirect: false
}, opt)
}
/**
* Update the options of Ajax
*
* @param {any} opt
*
* @memberOf Ajax
*/
update (opt) {
if (opt) {
this.options = Object.assign(
{},
this.options,
opt
)
}
}
/**
* Trigger the request
*
* @param {Object} opt
* @returns {Promise}
*
* @memberOf Ajax
*/
fetch (opt) {
let self = this
let options = opt
? Object.assign({}, self.options, opt)
: self.options
let settings = {
url: options.path,
baseURL: options.baseURL,
method: options.method,
params: options.params,
data: options.data,
validateStatus (status) {
return status >= 200 && status < 300
}
}
if (!options.cache && options.method === 'get') {
settings.params.t = Date.now()
}
// make the key
let key = `${settings.url}_${settings.method}`
// set Authorization headers
axios.defaults.headers.common['Authorization'] = AuthToken.get()
// before send
if (typeof options.before === 'function') {
options.before()
}
// make the request
instance[key] = axios(settings)
// catch error
instance[key].catch(error => {
if (error.response.status === 401) {
self.handleGuest(error.response, options)
} else {
self.handleException(error.response, options)
}
})
// handle success
instance[key].then(response => {
self.handleResponse(response, options)
}).then(options.complete)
return instance[key]
}
/**
* Handle the response data under http status 200
*
* @param {Object} response
* @param {Object} options
*
* @memberOf Ajax
*/
handleResponse (response, options) {
let self = this
if (response.data) {
if (response.data.status === '100000') {
if (typeof options.success === 'function') {
options.success(response.data)
}
} else if (response.data.status === '000000') {
self.handleGuest(response, options)
} else {
self.handleFail(response, options)
}
} else {
self.handleException(response, options)
}
}
/**
* Handle the response data.status is not `100000`
*
* @param {Object} response
* @param {Object} options
*
* @memberOf Ajax
*/
handleFail (response, options) {
console.log(response)
if (typeof options.fail === 'function') {
options.fail(response)
}
if (typeof options.complete === 'function') {
options.complete(response)
}
if (options.toast) {
let text = response.statusText
let message = response.data.message || {}
let msg = message.desc || text
toast.log([msg])
}
}
/**
* Handle the response data.status is `200000`
*
* @param {Object} response
* @param {Object} options
*
* @memberOf Ajax
*/
handleGuest (response, options) {
if (typeof options.complete === 'function') {
options.complete(response)
}
if (options.toast) {
toast.log([Vue.t('login.guest')])
}
AuthToken.remove()
window.location = BASE + '#/login'
}
/**
* Handle http status not 200
*
* @param {Object} response
* @param {Object} options
*
* @memberOf Ajax
*/
handleException (response, options) {
console.log(response)
if (typeof options.fail === 'function') {
options.fail(response)
}
if (typeof options.complete === 'function') {
options.complete(response)
}
if (options.toast) {
let path = options.path
let text = response.statusText
text = text ? `: ${text}` : ''
toast.log([
Vue.t('common.path'),
path,
Vue.t('exception.occur') + text + ',',
Vue.t('exception.retry')
])
}
}
}
export default Ajax
import Local from './storage'
const PREFIX = ''
const KEY = 'AUTH_TOKEN'
const AuthToken = {
get (prefix = PREFIX) {
let ret = Local.getItem(KEY) || ''
if (ret) {
ret = prefix + ret
}
return ret
},
set (token = '') {
if (token) {
Local.setItem(KEY, token)
} else {
this.remove()
}
},
remove () {
Local.removeItem(KEY)
}
}
export default AuthToken
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.