From 2dbb3e275a32e777452587db34711a30b9aef5d2 Mon Sep 17 00:00:00 2001 From: Pixeladed Date: Tue, 20 Oct 2020 09:51:53 +0800 Subject: [PATCH] feat(settings): add settings to use payload as error instead --- src/index.ts | 15 ++++++++++----- src/reducers.ts | 6 +++++- src/settings.ts | 14 ++++++++++++++ src/types.ts | 6 +++++- 4 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 src/settings.ts diff --git a/src/index.ts b/src/index.ts index 7babbd4..63291c0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,12 +1,17 @@ import * as selectors from './selectors'; import * as reducers from './reducers'; import { getInitialState } from './state'; +import { AsyncAdapterOptions } from './types'; +import { setSettings } from './settings'; -const createAsyncAdapter = () => ({ - ...reducers, - getSelectors: () => selectors, - getInitialState, -}); +const createAsyncAdapter = (options: Partial) => { + setSettings(options); + return { + ...reducers, + getSelectors: () => selectors, + getInitialState, + }; +}; export * from './types'; export default createAsyncAdapter; diff --git a/src/reducers.ts b/src/reducers.ts index 3cc3ed3..004ca77 100644 --- a/src/reducers.ts +++ b/src/reducers.ts @@ -1,6 +1,7 @@ import { AsyncThunk } from '@reduxjs/toolkit'; import { AsyncState, AsyncStatus } from './types'; import { getDefaultStatus } from './utils'; +import { getSettings } from './settings'; /** * Handle async status updates for an async thunk pending action @@ -53,9 +54,12 @@ export const handleRejected = ( const { typePrefix } = asyncThunk; const currentStatus = state.status[typePrefix] || getDefaultStatus(typePrefix); + const settings = getSettings(); + const error = settings.usePayloadAsError ? action.payload : action.error; + const newStatus: AsyncStatus = { ...currentStatus, - error: action.error, + error, loaded: false, loading: false, }; diff --git a/src/settings.ts b/src/settings.ts new file mode 100644 index 0000000..9e2fc83 --- /dev/null +++ b/src/settings.ts @@ -0,0 +1,14 @@ +import { AsyncAdapterOptions } from './types'; + +const settings: AsyncAdapterOptions = { + usePayloadAsError: false, +}; + +export const getSettings = () => Object.freeze(settings); + +export const setSettings = (newSettings: Partial) => { + for (const property in newSettings) { + const key = property as keyof AsyncAdapterOptions; + settings[key] = newSettings[key]; + } +}; diff --git a/src/types.ts b/src/types.ts index 8d2da98..74fe779 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,5 +1,9 @@ import { SerializedError } from '@reduxjs/toolkit'; +export interface AsyncAdapterOptions { + usePayloadAsError: boolean; +} + export interface AsyncState { status: { [name: string]: AsyncStatus | undefined }; data: T; @@ -9,6 +13,6 @@ export interface AsyncStatus { name: string; loading: boolean; loaded: boolean; - error: SerializedError | undefined; + error: SerializedError | any | undefined; lastLoaded: string | undefined; }