Skip to content

Instantly share code, notes, and snippets.

@euglena1215
Created August 17, 2018 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save euglena1215/a6599bb16d9999ecfccf457a7513e04d to your computer and use it in GitHub Desktop.
Save euglena1215/a6599bb16d9999ecfccf457a7513e04d to your computer and use it in GitHub Desktop.
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