Skip to content

Instantly share code, notes, and snippets.

@AlexanderHentzsch
Created October 26, 2020 16:30
Show Gist options
  • Save AlexanderHentzsch/78fe1b00a13a8ddc9cd7e3dbdcdbb282 to your computer and use it in GitHub Desktop.
Save AlexanderHentzsch/78fe1b00a13a8ddc9cd7e3dbdcdbb282 to your computer and use it in GitHub Desktop.
Axios extension class for vuejs
import axios from 'axios';
let t;
export default class AxiosRequest {
constructor(url, requestMethod = 'GET', timeoutSeconds = 3, preload = false) {
this.successData = null;
this.errorMessage = null;
this.isCancel = false;
this.isError = false;
this.isLoading = false;
this.isTimeout = null;
this.lastChange = null;
this.showSuccess = false;
this.showError = false;
this.showCancel = false;
this.cancelSource = null;
this.url = url;
this.requestMethod = requestMethod.toLowerCase();
this._timeoutSeconds = timeoutSeconds;
this.preload = preload;
this._postData = {};
this.successCallback = function (d) {
return d;
};
this.cancelCallback = function (d) {
return d;
};
this.errorCallback = function (d) {
return d;
};
this.finallyCallback = function (d) {
return d;
};
if (!this.isUrl(this.url))
throw new Error('Ungültige URL.');
if (!['delete', 'get', 'head', 'options', 'patch', 'post', 'put'].includes(this.requestMethod))
throw new Error(`Ungültige Request-Methode: ${this.requestMethod}.`);
if (this.preload)
this.request();
}
get postData() {
return this._postData;
}
set postData(v) {
this._postData = v;
}
get timeoutSeconds() {
return this._timeoutSeconds;
}
set timeoutSeconds(v) {
if (Number.isInteger(v))
this._timeoutSeconds = v;
}
isUrl = function (url) {
try {
url = new URL(url);
} catch (e) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:"
}
validUrl(url = this.url) {
return new URL(url).href;
}
validPostData(d = this._postData) {
return (Object.keys(d).length > 0) ? d : false;
}
request(data = null) {
clearTimeout(t);
if (data)
this.postData = data;
this.successData = null;
this.errorMessage = null;
this.isCancel = false;
this.isError = false;
this.isLoading = true;
this.isTimeout = false;
this.showSuccess = false;
this.showError = false;
this.showCancel = false;
this.cancelSource = axios.CancelToken.source();
let config = {
method: this.requestMethod,
url: this.validUrl(),
cancelToken: this.cancelSource.token
};
if (this.validPostData())
config.data = this.validPostData();
axios(config)
.then(response => {
this.successData = response.data;
this.showSuccess = true;
if (typeof this.successCallback === "function")
this.successCallback(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
this.isCancel = true;
this.showCancel = true;
if (typeof this.cancelCallback === "function"){
this.cancelCallback(error);
}
} else {
this.isError = true;
this.showError = true;
if (error.response) {
const e = error.response.request.response;
this.errorMessage = this.isJsonString(e) ? JSON.parse(e) : e;
} else if (error.request) {
this.errorMessage = error.request;
} else {
this.errorMessage = error.message;
}
if (typeof this.errorCallback === "function")
this.errorCallback(error);
}
})
.finally(() => {
const d = (this.successData) ? this.successData : this.errorMessage;
this.finallyCallback(d);
this.isLoading = false;
this.lastChange = Date.now();
t = setTimeout(() => {
this.isTimeout = true;
}, this.timeoutSeconds * 1000);
})
}
cancel() {
if (this.cancelSource === null)
return;
this.cancelSource.cancel(`Operation canceled by the user.`);
}
isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment