/** * This file provides utility functions for creating reducers that manage async data (in other * words, data fetched via requests to the server). * * Data is stored using the following schema: * * { * isLoading {boolean} - True when an async fetch operation is in progress for the data. Allows * us to avoid duplicate simultaneous fetch operations and to provide feedback to the user * during load operations (loading animations) * error {*} - If the most recent async fetch operation failed, this field will hold that error * lastUpdated {Date} - The last time the data was updated. Allows us to detect data that has yet * to be fetched as well as stale data * data {*} - The actual data * } * * Lists of data are also supported. * * Note that the generated reducers all expects actions to be in the Flux Standard Action (FSA) format: * https://github.com/acdlite/flux-standard-action#example. */ import * as _ from "lodash"; import type { DataAction, ErrorAction, ItemMap, ReduxAction, SubstateItemData, SubstateListData, } from "./types"; /** * An identity function that is the default reduce function for the generic reducers in this module. * Given the state and an action, returns the action's payload as the new item state for this * substate of the store. * * @template [S=any] The type representation of the Redux store state. Can be a full or partial * typing; if the state type represents a partial slice of the store state, it is recommended to * declare that type as an interface. * @template [P=any] The payload type for the given action * @param state {S} The Redux store state * @param action {ReduxAction

} The action being reduced * @returns {P} The action payload */ const identityFn = (_: S, action: ReduxAction

): P => action.payload; /** * Returns a reducer that manages an async data item. * * @template [I=any] The type for an item returned by these selectors * @template [E=any] The error type for an item's failed load * @template [P=I] The action payload type * @param {function(I, ReduxAction

): I} [reduceFn] A function that produces a * new data entry, given the data entry from the current state and the action object. By default, * it is the identity function, which is only appropriate in cases where P = I; if you define an * explicit P type parameter, then you must also define this function parameter. * @return {function(SubstateItemData, ReduxAction): SubstateItemData} The reducer */ export const newAsyncDataReducer = ( // @ts-expect-error identityFn is the default behavior where P = I reduceFn: (state: I, action: DataAction

) => I = identityFn, ) => ( state: SubstateItemData, action: DataAction

| ErrorAction, ): SubstateItemData => { // Leave existing data intact while loading if (action.meta && action.meta.isLoading) { return { ...state, isLoading: true, }; } // Leave existing data intact when storing load errors if (action.error) { return { ...state, isLoading: false, error: action.payload, lastUpdated: new Date(), }; } // Replace the data and clear all metadata except `lastUpdated` on successful load return { lastUpdated: new Date(), // This typecast to ReduxAction is a bit misleading, because it's not always accurate; see // newAsyncListReducer below. If a caller wishes to solely update the error or loading state, as // in the previous two cases, then the payload is either irrelevant (loading) or E (error). We // assume that if neither of those things are true, then the payload is of the item type I. // Alternatively, if we do not intend for callers to use it this way, then we can force the // typecast in newAsyncListReducer instead. data: reduceFn(state.data, action as DataAction

), }; }; /** * Returns a reducer that stores/replaces a single item in an async data list. * * @template [I=any] The type for an item returned by these selectors * @template [E=any] The error type for an item's failed load * @param {function(P | E): string} keyFn A function that returns a unique key for the list item * @param {function(I, ReduxAction

): I} [itemReduceFn] A function that produces a * new data entry, given the data entry from the current state and the action object. By default, * it is the identity function, which is only appropriate in cases where P = I; if you define an * explicit P type parameter, then you must also define this function parameter. * @return {function(SubstateListData, ReduxAction): SubstateListData} The reducer */ export const newAsyncListItemReducer = ( keyFn: (payload: P | E) => string, // @ts-expect-error identityFn is the default behavior where P = I reduceFn: (state: I, action: ReduxAction

) => I = identityFn, ) => ( state: SubstateListData, action: DataAction

| ErrorAction, ): SubstateListData => { const itemKey = keyFn(action.payload); const currentItemState = _.get(state, `data.${itemKey}`) || {}; const newItemState = newAsyncDataReducer(reduceFn)(currentItemState, action); return { ...state, data: { ...state.data, [itemKey]: newItemState } }; }; /** * Returns a reducer that deletes a single item in an async data list. * * @template [I=any] The type for an item returned by these selectors * @template [E=any] The error type for an item's failed load * @template [P=any] The action payload type. May likely be *like* `I`, similar to the * newAsyncDataReducer or newAsyncListItemReducer versions, but the only requirement is that `keyFn` * be able to extract the correct key from the payload. * @param {function(P): string} keyFn - A function that returns a unique key for the list item * @return {function(SubstateListData, action: ReduxAction

)} - The reducer */ export const newAsyncListItemDeleteReducer = ( keyFn: (payload: P) => string, ) => (state: SubstateListData, action: ReduxAction

): SubstateListData => { const itemKey = keyFn(action.payload); // Create a copy of the state and then delete the specified item to ensure that the state is a // new reference const newState = { ...state, data: { ...state.data } } as SubstateListData; if (newState.data && newState.data[itemKey]) { delete newState.data[itemKey]; } return newState; }; /** * Returns a reducer that takes a list payload and stores it as an object, where each value is of * the format described at the top of this file. * * @template [I=any] The type for an item returned by these selectors * @template [E=any] The error type for an item's failed load * @template [LE=E] The error type for the list's failed load. May or may not be the same as `E`. * @param {function(I): string} keyFn - A function that returns a unique key for every * payload list item * @param {function(SubstateItemData, ReduxAction): I} [itemReduceFn] - A function that * produces a new data entry for a single item in the list, given the data entry from the current * item state and an action containing the item as its payload * @return {function(SubstateListData, ReduxAction): SubstateListData} - The reducer */ export const newAsyncListReducer = ( keyFn: (payload: P) => string, // @ts-expect-error identityFn is the default behavior where P = I itemReduceFn: (state: SubstateItemData, action: ReduxAction

) => I = identityFn, ) => ( state: SubstateListData, action: DataAction | ErrorAction, ): SubstateListData => { // Leave existing data intact but update metadata if necessary const newState: SubstateListData = newAsyncDataReducer, LE, P[]>( (currentState: ItemMap): ItemMap => currentState || {}, )(state, action); if (newState.isLoading || newState.error) { return newState; } // Replace all items with the new list on successful load newState.data = {}; const items = action.payload as P[]; // If items is null or undefined just give them empty data. We need to allow // null or undefined items for backwards compatibility. if (items === null || items === undefined) { return newState; } if (!Array.isArray(items)) { throw new Error("AsyncListReducer received non-array items as input."); } for (let i = 0, len = items.length; i < len; i++) { const item = items[i]; const itemKey = keyFn(item); const currentItemState = _.get(state, `data.${itemKey}`) || {}; const newItemState = newAsyncDataReducer(itemReduceFn)(currentItemState, { ...action, payload: item, } as DataAction

); newState.data[itemKey] = newItemState; } return newState; };