All files / src/hocs cache.js

64.6% Statements 73/113
51.06% Branches 24/47
70.59% Functions 24/34
64.86% Lines 72/111

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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291                                          4x 4x                 4x 4x 4x     4x 4x   4x           1x       1x     1x         1x 1x           3x     3x 3x 1x   2x 2x 2x   2x 1x           2x 2x     2x 2x 2x     2x 2x 1x           2x 2x                               3x 3x         3x                   3x   3x   3x   3x 3x 3x                                       1x               1x 1x     1x 1x 1x 1x   1x 1x                     1x   1x   1x     1x 1x                                   1x 1x     1x 1x 1x   1x           4x     4x 4x 4x 3x 3x       4x                               13x                                                       7x 7x       1x  
// @flow
import * as React from 'react';
import {mutate as defaultMutate, ActionManager as DefaultAciontManager} from '../action';
import {isCompleteContain, genPaths} from './route';
import { isArray } from 'lodash';
import mapValues from 'lodash/mapValues';
import {groupBy} from 'lodash';
import { OnDeployManager } from '../onDeployManager';
import type {Action, ActionType} from '../action/types';
import type {HOCProps} from './types';
 
type State = {
  [string]: *,
  dataChanged: Object,
}
 
export default function withCache(Com: React.ComponentType<*>, options: {
  mutate: typeof defaultMutate,
  ActionManager: DefaultAciontManager,
  onDeployManager: OnDeployManager
}) {
  const {mutate = defaultMutate, ActionManager = DefaultAciontManager} = options || {};
  return class ComWithCache extends React.Component<HOCProps, State> {
  actionManager: ?ActionManager;
  onDeployManager: OnDeployManager;
  subscribers: {
      [key: string]: Array<{id: string, callback: Function}>
    }
    subscribers = {};
    subscription: any;
    constructor(props: HOCProps) {
      super(props);
      const {routes, cacheActions, pattern, path} = this.props;
      Eif ((routes.length > 1 && isRoutesEndAtMe({routes, pattern, path})) ||
        cacheActions
      ) {
        this.actionManager = new ActionManager();
        this.onDeployManager = new OnDeployManager();
      }
      this.state = {
        dataChanged: {}
      };
    }
 
    addSubscriber = (key: string, id: string, callback: Function) => {
      const subscriber = {
        id,
        callback
      };
      Iif (this.subscribers[key]) {
        this.subscribers[key].push(subscriber);
      } else {
        this.subscribers[key] = [subscriber];
      }
    }
 
    unsubscribe = (key: string, subscriberId: string) => {
      this.subscribers[key] = this.subscribers[key].filter(subscriber => {
        return subscriber.id !== subscriberId;
      });
    }
 
    publish = (key: string, id?: string) => {
      // $FlowFixMe
      Iif (!this.actionManager) {
        return;
      }
      const data = this.state[key];
      if (!data) {
        return;
      }
      const actions = this.actionManager.getActions(key, id);
      const mutatedData = actions.reduce((result: any, action: Action<ActionType>) => {
        return mutate(result, action);
      }, data);
      (this.subscribers[key] || []).forEach(subscribe => {
        subscribe.callback(mutatedData);
      });
    }
 
    fetch = (key: string) => {
      // the data will be mutated by cached actions
      const {fetch} = this.props;
      Iif (!this.actionManager) {
        return fetch(key);
      }
      const actions = this.actionManager.getActions(key);
      return fetch(key).then(data => {
        this.setState({
          [key]: data
        });
        this._subscribe(key);
        return actions.reduce((result: any, action: Action<ActionType>) => {
          return mutate(result, action);
        }, data);
      });
    }
 
    _subscribe = (key: string) => {
      const {subscribe} = this.props;
      this.subscription = subscribe(key, (data) => {
        this.setState({
          [key]: data
        }, () => this.publish(key));
      });
    }
 
    _unsubscribe = () => {
      if (this.subscription) {
        this.subscription.unsubscribe();
      }
    }
 
    request = (action: Array<Action<ActionType>> | Action<ActionType>): Promise<*> => {
      // use action manager cache the actions
      // update state.actions
      const {request} = this.props;
      Iif (!this.actionManager) {
        // $FlowFixMe
        return request(action);
      }
      let key, id;
      Iif (isArray(action)) {
        // $FlowFixMe
        action.forEach(ac => {
          // $FlowFixMe
          this.actionManager.addAction(ac);
        });
        key = action[0].payload.key;
        id = action[0].payload.id;
      } else {
        // $FlowFixMe
        this.actionManager.addAction(action);
        // $FlowFixMe
        key = action.payload.key;
        // $FlowFixMe
        id = action.payload.id;
      }
      this.updateDataChanged();
      this.publish(key, id);
      return Promise.resolve();
    }
 
    onDeploy = (key: string, callback: any) => {
      const {onDeploy} = this.props;
      if (!this.onDeployManager) {
        return onDeploy(key, callback);
      }
      return this.onDeployManager.registerCallback(key, callback);
    }
 
    removeOnDeploy = (key: string, callbackId: string) => {
      const {removeOnDeploy} = this.props;
      if (!this.onDeployManager) {
        return removeOnDeploy(key, callbackId);
      }
      return this.onDeployManager.unregisterCallback(key, callbackId);
    }
 
    _executeOnDeployCallback = (key: string, value: any) => {
      return this.onDeployManager.execute({
        key,
        value
      });
    }
 
    deploy = (key: string, id?: string): Promise<*> => {
      // request cached actions
      const {request, deploy, pattern} = this.props;
      Iif (!this.actionManager) {
        return deploy(key, id);
      }
      const originData = this.state[key];
      let actions = this.actionManager.getActions(key, id);
      const mutatedData = actions.reduce((result: any, action: Action<ActionType>) => {
        return mutate(result, action);
      }, originData);
      const {error} = this._executeOnDeployCallback(key, mutatedData[key]);
      Iif (error) {
        return Promise.reject();
      }
      // actions = actions.map(action => {
      //   const {key, value} = action.payload;
      //   hasError = hasError || error;
      //   action.payload.value = data;
      //   return action;
      // });
 
      // $FlowFixMe
      this.actionManager.removeActions(key, id);
 
      this.updateDataChanged();
      // $FlowFixMe
      request(actions);
      // if this cache is on the first layer,
      // it should call the deploy after request
      Eif (pattern.split('.').length === 1) {
        return deploy(key, id);
      }
      return Promise.resolve();
    }
 
    reset = (key: string, id?: string): Promise<*> => {
      // remove sepicfic cached actions in actionManager
      const {reset} = this.props;
      if (!this.actionManager) {
        return reset(key, id);
      }
      this.actionManager.removeActions(key, id);
      this.updateDataChanged();
      this.publish(key, id);
      return Promise.resolve();
    }
 
    subscribe = (key: string, callback: Function) => {
      const {subscribe} = this.props;
      Iif (!this.actionManager) {
        return subscribe(key, callback);
      }
      const id = genSubscriberId();
      this.addSubscriber(key, id, callback);
      return {
        unsubscribe: () => {
          this.unsubscribe(key, id);
        }
      }
    }
 
    updateDataChanged = () => {
      Iif (!this.actionManager) {
        return;
      }
      const actions = this.actionManager.getActions();
      let dataChanged = groupBy(actions, (action => action.payload.key));
      dataChanged = mapValues(dataChanged, value => {
        Eif (value[0].type === 'UPDATE_OBJECT') {
          return true;
        }
        return value.map(v => v.payload.id);
      });
      this.setState({dataChanged});
    }
 
    updateQuery = (paths: Array<string>, args: Object) => {
      const {updateQuery} = this.props;
      return updateQuery(paths, args)
        .then(reWatch => {
          if (reWatch) {
            this._unsubscribe();
            this.fetch(paths[0]);
          }
          return reWatch;
        });
    }
 
    render() {
      return (
        <Com
          {...this.props}
          fetch={this.fetch}
          request={this.request}
          deploy={this.deploy}
          reset={this.reset}
          subscribe={this.subscribe}
          updateQuery={this.updateQuery}
          onDeploy={this.onDeploy}
          removeOnDeploy={this.removeOnDeploy}
          dataChanged={this.state.dataChanged}
          
        />
      );
    }
  }
}
 
export function isRoutesEndAtMe({
  routes,
  path,
  pattern
}: {
  routes: Array<string>,
  path: string,
  pattern: string
}): boolean {
  const paths = genPaths(path, pattern);
  return (paths.length === routes.length && isCompleteContain(paths, routes));
}
 
export function genSubscriberId() {
  return Math.random().toString(36).substr(2, 7);
}