Skip to content

Instantly share code, notes, and snippets.

@sagormax
Created October 17, 2019 04:49
Show Gist options
  • Select an option

  • Save sagormax/c42ef82c449f684979c2f468d77aa523 to your computer and use it in GitHub Desktop.

Select an option

Save sagormax/c42ef82c449f684979c2f468d77aa523 to your computer and use it in GitHub Desktop.
JavaScript Abstruct API
import { BASE_PATH, RESPONSE_OK } from '../../constants/Api';
import axios from 'axios';
export default class AbstractApi {
constructor() {
this.api = axios;
this.path = '';
this.data = {};
}
/**
* Get API Response
* @method GET
* @return {Promise<void>}
*/
async get() {
return await this.api.get(BASE_PATH + this.path)
.then(response => {
// If response not ok
// throw an error exception
if (response.data.code !== RESPONSE_OK) {
this.handleResponseError(response.data);
}
return response.data;
})
.catch(error => {
this.handleError(error);
});
};
/**
* Get API Response
* @method POST
* @return {Promise<void>}
*/
async post(mail_data) {
return await this.api.post(BASE_PATH + this.path, mail_data)
.then(response => {
// If response not ok
// throw an error exception
if (response.data.code !== RESPONSE_OK) {
this.handleResponseError(response.data);
}
return response.data;
})
.catch(error => {
this.handleError(error);
});
};
/**
* Throw HTTP Error
* @param response
*/
handleResponseError = (response) => {
console.log("HTTP error, status = " + response.status + ' & code = ' + response.code);
};
/**
* Log Network/API response error
* @param error
*/
handleError = (error) => {
console.log(error.message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment