@ampush/centaurus
Version:
Centaurus, is an Ampush repository designed to house common UI components, JS classes, templates and API methods in a central place that can be imported and reused across other Ampush partner repositories as needed.
55 lines (53 loc) • 2.34 kB
JavaScript
const errorFn = (err) => {
console.info('%c ERROR! body is type %s, needs to be an object.', 'color:maroon;background:gray', typeof err);
return err;
};
const successFn = ({ data }) => {
const { error, code, message } = data;
if (error || code) {
return Object.assign(Object.assign({}, data), { error: !!error || !!code, code, message });
}
return data;
};
const promise = ({ sError, sSuccess }) =>
// eslint-disable-next-line compat/compat
new Promise((resolve, reject) => (sError ? reject(errorFn(sError)) : resolve(successFn(sSuccess))));
const valid = (item) => typeof item === 'object';
class AxiosRequest {
constructor(host) {
this.validBody = valid;
this.post = ({ body, service, uri }) => {
return valid(body)
? this._sendRequest({ body, method: 'POST', service, uri, host: this.host })
: promise({ sError: body });
};
this.put = ({ body, service, uri }) => {
return valid(body)
? this._sendRequest({ body, method: 'PUT', service, uri, host: this.host })
: promise({ sError: body });
};
this.get = ({ service, uri }) => this._sendRequest({ method: 'GET', service, uri, host: this.host });
this.delete = ({ body, service, uri }) => this._sendRequest({ method: 'DELETE', body, service, uri, host: this.host });
this._sendRequest = (request) => {
if (!request) {
return promise({ sError: 'request empty' });
}
const { body, host, method, service, uri } = request;
if (!method || !uri) {
return promise({ sError: 'method, or uri is empty' });
}
const url = [host, service, uri].filter((v) => v).join('/');
const req = Object.assign({ method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } }, (body ? { data: body } : {}));
this.cancelTokenSource = AxiosRequest.CancelToken.source();
return AxiosRequest(req)
.then((resp) => {
return promise({ sSuccess: resp });
})
.catch((err) => {
return promise({ sError: err });
});
};
this.host = host;
}
}
export default AxiosRequest;