UNPKG

@iel/axios-ext-response-wrap

Version:

Axios response result wrapper.

55 lines (54 loc) 2.93 kB
import { createShallowAxiosInstance, EVENT_STORE_KEY, onResponse, onResponseError } from '@iel/axios-ext'; import { assignSafely, deleteKeys, helperCreateEventStoreManager, isBoolean, isFunction, isPromise, isPlainObject, noop } from '@iel/axios-ext-utils'; const getValidOptions = (options = {}) => { const _options = assignSafely(options); if (!isBoolean(_options.globalWithResponseWrap)) _options.globalWithResponseWrap = !!_options.globalWithResponseWrap; if (!isPlainObject(_options.wrapper)) _options.wrapper = { transformResponseData: undefined, transformResponseError: undefined }; if (!isFunction(_options.transformResponseData)) _options.transformResponseData = _options.wrapper.transformResponseData; if (!isFunction(_options.transformResponseError)) _options.transformResponseError = _options.wrapper.transformResponseError; return _options; }; const getValidArgs = (args = {}, options = {}) => { const _args = assignSafely({ skipGlobalResponseWrap: !options.globalWithResponseWrap, skipGlobalErrorWrap: !options.globalWithResponseWrap }, args); if (!isBoolean(_args.skipGlobalResponseWrap)) _args.skipGlobalResponseWrap = !!_args.skipGlobalResponseWrap; if (!isBoolean(_args.skipGlobalErrorWrap)) _args.skipGlobalErrorWrap = !!_args.skipGlobalErrorWrap; return _args; }; const evtStoreManager = helperCreateEventStoreManager('ResponseWrap'); const AxiosExtResponseWrapPlugin = function (axiosExt, options) { const baseOptions = getValidOptions(options); const instance = axiosExt.instance; const withResponseWrap = function (args) { const shallowInstance = createShallowAxiosInstance(axiosExt, this); evtStoreManager.set(shallowInstance[EVENT_STORE_KEY], getValidArgs(args, baseOptions)); deleteKeys(shallowInstance, ['withResponseWrap']); return shallowInstance; }; instance.withResponseWrap = withResponseWrap; onResponse(({ $eventStore, response, config, resolve }) => { var _a; const eventStore = (_a = evtStoreManager.get($eventStore)) !== null && _a !== void 0 ? _a : getValidArgs({}, baseOptions); if (eventStore.skipGlobalResponseWrap || !isFunction(baseOptions.transformResponseData)) return; resolve(baseOptions.transformResponseData(response, config)); }); onResponseError(({ $eventStore, error, config, returnValue, resolve }) => { var _a; const eventStore = (_a = evtStoreManager.get($eventStore)) !== null && _a !== void 0 ? _a : getValidArgs({}, baseOptions); if (eventStore.skipGlobalErrorWrap || !isFunction(baseOptions.transformResponseError)) return; if (isPromise(returnValue)) returnValue.catch(noop); resolve(baseOptions.transformResponseError(error, config)); }); }; export default AxiosExtResponseWrapPlugin;