All files create-items.ts

100% Statements 71/71
100% Branches 27/27
100% Functions 25/25
100% Lines 67/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 2501x 1x 1x                 1x                                 1x 16x 16x 16x 16x             16x   3x 3x     3x 3x   3x               3x             1x             2x 2x       3x               1x                     1x     16x   16x 16x 1x   1x   2x 2x   2x       16x 1x   1x   1x       2x       2x 2x 2x         16x                     1x 16x     16x 8x 8x   8x   3x   3x       3x       3x         1x   1x       1x         1x         1x 1x 1x     1x         2x   3x 3x         2x   1x                                                           1x   30x   32x   16x       16x          
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import {
  AnyAction,
  AnyItem,
  ensureArray,
  defaultGenId,
  Constants,
  Dispatch,
  getType
} from './utils';
import {
  CreateStateRxApi,
  CreateStateRxOpts,
  createStateRx
} from './create-staterx';
 
type ItemState<Item> = {
  [key: string]: Item | undefined;
};
 
type ItemsT<T> = Partial<T> | Array<Partial<T>>;
 
type PartialWithId<T> = Partial<T> & { id: string };
 
/*******************************************************
 * Actions
 *******************************************************/
const createActions = <T>({
  constant,
  generateId,
  defaultItem,
  dispatch
}: {
  constant: Constants;
  generateId: () => string;
  defaultItem: Partial<T> | (() => Partial<T>);
  dispatch: Dispatch;
}) => {
  return {
    create: (items?: ItemsT<T>) => {
      const ensureItem = (items || {}) as T;
      const newCreateItems = ensureArray<PartialWithId<T>>(ensureItem).map(
        (item) => {
          // istanbul ignore else
          if (item.id === undefined) {
            item.id = generateId();
          }
          return {
            ...(typeof defaultItem === 'function'
              ? defaultItem()
              : defaultItem),
            ...item
          };
        }
      );
      return dispatch({
        type: constant.CREATE,
        items: (newCreateItems as unknown) as T[]
      });
    },
 
    update: (items: ItemsT<T>) => {
      return dispatch({
        type: constant.UPDATE,
        items: ensureArray<T>(items)
      });
    },
 
    remove: (items: ItemsT<T> | string | string[]) => {
      const wrappedItems = !Array.isArray(items) ? [items] : items;
      return dispatch({
        type: constant.REMOVE,
        items: ensureArray<T>(
          typeof wrappedItems[0] === 'string'
            ? (wrappedItems as string[]).map((id: string) => ({ id }))
            : // istanbul ignore next
              wrappedItems
        )
      });
    },
 
    replace: (items: ItemsT<T>) => {
      return dispatch({
        type: constant.REPLACE,
        items: ensureArray<T>(items)
      });
    }
  };
};
 
/*******************************************************
 * Selectors
 *******************************************************/
const createSelectors = <T extends AnyItem, S>(
  state$: Observable<ItemState<T>>
) => {
  const all$ = state$.pipe(map((state) => Object.values(state) as T[]));
 
  const byId = (id: string) => state$.pipe(map((state) => state[id]));
  const byIds = (ids: Array<string | null | undefined>) =>
    state$.pipe(
      map((state) =>
        ids.reduce<ItemState<T>>((acc, id) => {
          // istanbul ignore else
          if (id) {
            acc[id] = state[id];
          }
          return acc;
        }, {})
      )
    );
  const mapByKey = (key: string) =>
    state$.pipe(
      map((state) => {
        const items = state;
 
        return Object.values(items).reduce<{
          [key: string]: T[] | undefined;
        }>((acc, item) => {
          // istanbul ignore if
          if (!item) {
            return acc;
          }
 
          const arr = (acc[item[key]] = acc[item[key]] || []);
          arr.push(item);
          return acc;
        }, {});
      })
    );
 
  return {
    all$,
    byId,
    byIds,
    mapByKey
  };
};
 
/*******************************************************
 * Reducer
 *******************************************************/
const createReducer = <T extends AnyItem>({
  constant
}: {
  constant: Constants;
}) => (state: any, action: AnyAction) => {
  const items = ensureArray<T>('items' in action ? action.items : []);
  const type = getType(action);
 
  switch (type) {
    case constant.CREATE:
      const newCreateItems = (items as T[]).reduce<{ [id: string]: T }>(
        (acc, item) => {
          acc[item.id] = {
            ...(state[item.id] || {}),
            ...item
          };
          return acc;
        },
        {}
      );
      return {
        ...state,
        ...newCreateItems
      };
    case constant.UPDATE:
      const newUpdatedItems = (items as T[]).reduce<{ [id: string]: T }>(
        (acc, item) => {
          acc[item.id] = {
            ...state[item.id],
            ...item
          };
          return acc;
        },
        {}
      );
 
      return {
        ...state,
        ...newUpdatedItems
      };
    case constant.REPLACE:
      const newReplaceItems = items.reduce<{ [id: string]: T }>((acc, item) => {
        acc[item.id] = item as T;
        return acc;
      }, {});
 
      return {
        ...state,
        ...newReplaceItems
      };
    case constant.REMOVE:
      const newRemoveItems = items.reduce(
        (acc, item) => {
          delete acc[item.id];
          return acc;
        },
        { ...state }
      );
 
      return newRemoveItems;
    default:
      return state;
  }
};
 
/*******************************************************
 * Item State
 *******************************************************/
export interface CreateItemOpts<T, S, E>
  extends CreateStateRxOpts<E, StateRxItems<T, S>, S> {
  /** A default item to shallowly merge into newly created items. */
  defaultItem?: Partial<T> | (() => Partial<T>);
  /** A custom method for generating IDs for new items. */
  generateId?: () => string;
}
 
export interface StateRxItems<T, S> extends CreateStateRxApi<S> {
  create: (items?: ItemsT<T>) => AnyAction<string>;
  update: (items: ItemsT<T>) => AnyAction<string>;
  replace: (items: ItemsT<T>) => AnyAction<string>;
  remove: (items: ItemsT<T> | string | string[]) => AnyAction<string>;
  all$: Observable<T[]>;
  byId: (id: string) => Observable<T | undefined>;
  byIds: (ids: (string | null | undefined)[]) => Observable<ItemState<T>>;
  mapByKey: (
    key: keyof T
  ) => Observable<{
    [key: string]: T[] | undefined;
  }>;
}
 
export const createItems = <T extends AnyItem, E>(
  initialState: ItemState<T>,
  options: CreateItemOpts<T, ItemState<T>, E> = {}
) => {
  const { generateId = defaultGenId, defaultItem = {} } = options;
 
  return createStateRx(initialState, options, {
    state$: new BehaviorSubject<ItemState<T>>(initialState),
    constants: ['CREATE', 'REPLACE', 'REMOVE', 'UPDATE'],
    createActions: (props) =>
      createActions({ ...props, generateId, defaultItem }),
    createReducer,
    createSelectors
  });
};