@yoroi/common
Version:
The Common package of Yoroi SDK
149 lines (145 loc) • 5.05 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fetchData = void 0;
var _axios = _interopRequireWildcard(require("axios"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// Module augmentation to extend AxiosRequestConfig
/**
* Performs an HTTP request using Axios based on the specified configuration.
* This function simplifies making HTTP requests by handling different
* request methods and their respective data and headers.
*
* @param config - The configuration object for the request.
* This includes the URL, HTTP method, optional data, and headers.
* The type of `config` varies based on the HTTP method:
* - For `GET` requests, `data` should not be provided.
* - For `POST`, `PUT`, and `DELETE` requests, `data` is optional.
*
* @returns A `Promise` that resolves to the response data on a successful request
* or an error object on failure. The error object includes the HTTP status
* code and error message.
*
* @template T - The expected type of the response data.
* @template D - The type of the data to be sent with the request (for `POST`, `PUT`, `DELETE`).
*
* @example
* ```typescript
* // Example of a GET request
* fetchData<{ someDataType }>({
* url: 'https://example.com/data',
* }).then(response => {
* // Handle response
* }).catch(error => {
* // Handle error
* })
* ```
*
* @example
* ```typescript
* // Example of a POST request with data
* fetchData<{ someDataType }, { somePayloadType }>({
* url: 'https://example.com/data',
* method: 'post',
* data: {...somePayload}
* }).then(response => {
* // Handle response
* }).catch(error => {
* // Handle error
* })
* ```
*/
const fetchData = (config, fetcherConfig) => {
const method = config.method ?? 'get';
const isNotGet = method !== 'get';
const axiosConfig = {
...fetcherConfig,
url: config.url,
method: method,
headers: config.headers ?? {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
},
...(isNotGet && 'data' in config && {
data: config.data
}),
// updated by the interceptors
metadata: {
startTime: new Date().getTime(),
duration: 0
}
};
return (0, _axios.default)(axiosConfig).then(_ref => {
let {
status,
data
} = _ref;
return {
tag: 'right',
value: {
status,
data
}
};
}).catch(error => {
if (error.response) {
const status = error.response.status;
const message = error.response.statusText;
const responseData = error.response.data;
return {
tag: 'left',
error: {
status,
message,
responseData
}
};
} else if (error.request) {
return {
tag: 'left',
error: {
status: -1,
message: 'Network (no response)',
responseData: null
}
};
} else {
return {
tag: 'left',
error: {
status: -2,
message: `Invalid state: ${error.message}`,
responseData: null
}
};
}
});
};
/* istanbul ignore next */
exports.fetchData = fetchData;
_axios.default.interceptors.request.use(config => {
config.metadata = {
startTime: new Date().getTime(),
duration: 0
};
return config;
}, error => {
return Promise.reject(error);
});
/* istanbul ignore next */
_axios.default.interceptors.response.use(response => {
if (response.config.metadata) {
const endTime = new Date().getTime();
const startTime = response.config.metadata.startTime;
const duration = endTime - startTime;
response.config.metadata.duration = duration;
}
return response;
}, error => {
return Promise.reject(error);
});
//# sourceMappingURL=fetchData.js.map