Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import fetchival from 'fetchival';
- import _ from 'lodash';
- import * as sessionSelectors from 'services/session/selectors';
- import apiConfig from './config';
- /*
- * Get message exception
- *
- * @param {String} exception error
- * @return error
- */
- export const exceptionExtractError = (exception) => {
- if (!exception.Error) return false;
- let error = false;
- const errorKeys = Object.keys(exception.Errors);
- if (errorKeys.length > 0) {
- error = exception.Errors[errorKeys[0]][0].message;
- }
- return error;
- };
- /*
- * Connect to api
- *
- * @param {String} endPoint end path of api url
- * @param {Object} payload data want to send
- * @param {String} method method use to send api
- * @param {Object} headers header want to send
- * @throw {e}
- */
- export const fetchApi = (endPoint, payload = {}, method = 'get', headers = {}) => {
- const accessToken = sessionSelectors.get().tokens && sessionSelectors.get().tokens.access.value;
- if (!accessToken) {
- payload.client_id = apiConfig.clientId;
- payload.client_secret = apiConfig.clientSecret;
- }
- return fetchival(`${apiConfig.url}${endPoint}`, {
- headers: _.pickBy({
- ...(accessToken ? {
- Authorization: `Bearer ${accessToken}`,
- } : {}),
- ...headers,
- }, item => !_.isEmpty(item)),
- })[method.toLowerCase()](payload)
- .catch((e) => {
- throw e;
- });
- };
- /*
- * Connect to api have image
- *
- * @param {String} endPont end path of api url
- * @param {Object} payload data want to send
- * @param {String} method method use to send api
- * @param {Object} header header want to send
- */
- export const fetchApiWithImage = (
- endPoint,
- payload = {},
- method = 'post',
- headers = { Accept: 'application/json', 'Content-Type': 'multipart/form-data' },
- ) => {
- const accessToken = sessionSelectors.get().tokens && sessionSelectors.get().tokens.access.value;
- return new Promise(
- (resolve, reject) => {
- const xhr = new XMLHttpRequest();
- xhr.open(method, `${apiConfig.url}${endPoint}`);
- xhr.responseType = 'json';
- const formdata = payload;
- xhr.onreadystatechange = () => {
- if (xhr.readyState === XMLHttpRequest.DONE) {
- resolve(xhr.response);
- }
- };
- xhr.setRequestHeader('Authorization', `Bearer ${accessToken}`);
- xhr.send(formdata);
- },
- );
- };
Advertisement
Add Comment
Please, Sign In to add comment