Created
August 17, 2018 09:19
-
-
Save euglena1215/a6599bb16d9999ecfccf457a7513e04d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class RestClient { | |
axios: any; | |
constructor(baseUrl: string) { | |
const axiosBase = require("axios"); | |
const csrfToken = (<HTMLMetaElement>document.querySelector("meta[name=csrf-token]")).content; | |
this.axios = axiosBase.create({ | |
baseURL: baseUrl, | |
timeout: 1000, | |
headers: { | |
"Content-Type": "application/json", | |
"X-CSRF-TOKEN": csrfToken, | |
}, | |
}); | |
} | |
get( | |
path: string, | |
params: object, | |
successed: (res: object) => void, | |
errored: (res: object) => void, | |
always = () => {} | |
) { | |
return this.axios | |
.get(path, { params: params }) | |
.then((result: object) => { | |
console.log(`GET ${this.axios.baseURL}/${path}`); | |
console.log(`result: ${JSON.stringify(result)}`); | |
successed(result); | |
}) | |
.catch((error: object) => { | |
console.log(`ERROR! GET ${this.axios.baseURL}/${path}`); | |
console.log(`error: ${JSON.stringify(error)}`); | |
errored(error); | |
}) | |
.then(always()); | |
} | |
post( | |
path: string, | |
params: object, | |
successed: (res: object) => void, | |
errored: (res: object) => void, | |
always = () => {} | |
) { | |
return this.axios | |
.post(path, params) | |
.then((result: object) => { | |
console.log(`POST ${this.axios.baseURL}/${path}`); | |
console.log(`result: ${JSON.stringify(result)}`); | |
successed(result); | |
}) | |
.catch((error: object) => { | |
console.log(`ERROR! POST ${this.axios.baseURL}/${path}`); | |
console.log(`error: ${JSON.stringify(error)}`); | |
errored(error); | |
}) | |
.then(always()); | |
} | |
delete( | |
path: string, | |
params: object, | |
successed: (res: object) => void, | |
errored: (res: object) => void, | |
always = () => {} | |
) { | |
return this.axios | |
.delete(path, { data: { params } }) | |
.then((result: object) => { | |
console.log(`DELETE ${this.axios.baseURL}/${path}`); | |
console.log(`result: ${JSON.stringify(result)}`); | |
successed(result); | |
}) | |
.catch((error: object) => { | |
console.log(`ERROR! DELETE ${this.axios.baseURL}/${path}`); | |
console.log(`error: ${JSON.stringify(error)}`); | |
errored(error); | |
}) | |
.then(always()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment