All files / hocs id.js

0% Statements 0/70
0% Branches 0/51
0% Functions 0/18
0% Lines 0/64

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                                                                                                                                                                                                                                                                                                                                   
// @flow
 
import * as React from 'react';
import RefId from 'canner-ref-id';
import {createEmptyData} from 'canner-helpers';
import {get, update} from 'lodash';
import {Spin, Icon} from 'antd';
 
import type {HOCProps, Args} from './types';
import type {Query} from '../query';
 
const antIcon = <Icon type="loading" style={{fontSize: 24}} spin />;
 
type State = {
  canRender: boolean,
  refId: RefId
};
 
export default function connectId(Com: React.ComponentType<*>) {
  return class ComponentConnectId extends React.Component<HOCProps, State> {
    refId: RefId;
    query: Query;
    reset: Function;
    args: Args;
 
    constructor(props: HOCProps) {
      super(props);
      const {routerParams, pattern, refId, keyName, routes} = props;
      let myRefId = refId;
      // route to children
      if (routerParams.operator === 'create' && pattern === 'array') {
        this.state = {
          canRender: false,
          refId: refId
        };
      } else if (pattern === 'array' && routes.length > 1) {
        // in this case,
        // this hoc will fetch data with query {where: {id: id}} in componentDidMount
        // so the index in refId must be 0
        this.state = {
          canRender: false,
          refId: refId.child(`${keyName}/0`)
        };
      } else {
        myRefId = myRefId ? myRefId.child(keyName) : new RefId(keyName);
        this.state = {
          canRender: true,
          refId: myRefId
        };
      }
    }
 
    UNSAFE_componentWillReceiveProps(props: HOCProps) {
      const {routerParams: {operator}, pattern, items, keyName, routes, updateQuery} = props;
      if (operator === 'create' && this.props.routerParams.operator === 'update' && pattern ==='array') {
        // posts => posts?op=create
        let value = createEmptyData(items);
        update(value, 'id', id => id || randomId());
        update(value, '__typename', typename => typename || null);
        this.setState({
          canRender: false
        });
        this.createArray(keyName, value);
      }
 
      if (operator === 'update' && this.props.routerParams.operator === 'create' && pattern === 'array') {
        // posts?op=create => posts
        this.setState({
          refId: new RefId(keyName)
        });
      }
 
      if (pattern === 'array' && routes.length > 1 && this.props.routes.length === 1) {
        // posts => posts/<postId>
        this.setState({
          refId: new RefId(`${keyName}/0`)
        });
        this.fetchById(routes[1]);
      }
 
      if (pattern === 'array' && routes.length === 1 && this.args && this.props.routes.length > 1) {
        // posts/<postId> => posts
        this.setState({
          refId: new RefId(`${keyName}`)
        });
        updateQuery([keyName], this.args);
        delete this.args;
      }
    }
 
    componentDidMount() {
      const {routerParams, pattern, keyName, items, routes} = this.props;
      if (routerParams.operator === 'create' && pattern === 'array') {
        // posts?op=create
        let value = createEmptyData(items);
        update(value, 'id', id => id || randomId());
        update(value, '__typename', typename => typename || null);
        this.createArray(keyName, value);
      } else if (pattern === 'array' && routes.length > 1) {
        // posts/<postId>/title
        this.fetchById(routes[1]);
      } else {
        this.setState({
          canRender: true
        });
      }
    }
 
    fetchById = (id: string) => {
      const {query, keyName, updateQuery} = this.props;
      const paths = [keyName];
      const queries = query.getQueries(paths).args || {pagination: {first: 10}};
      const variables = query.getVairables();
      this.args =(queries, v => variables[v.substr(1)]);
      updateQuery(paths, {
        ...this.args,
        where: {id: id},
      });
      fetch(keyName)
        .then(() => {
          this.setState({
            canRender: true
          });
        });
    }
 
    createArray = (keyName: string, value: any) => {
      const {fetch, request} = this.props;
      fetch(keyName)
        .then(result => {
          const size = get(result, [keyName, 'edges']).length;
          // $FlowFixMe
          return request({
            type: 'CREATE_ARRAY',
            payload: {
              id: value.id,
              value,
              key: keyName,
            }
          }).then(() => size);
        })
        .then(size => {
          this.setState({
            canRender: true,
            refId: new RefId(`${keyName}/${size}`)
          });
        });
    }
 
    render() {
      let {canRender, refId} = this.state;
      if (!canRender) return <Spin indicator={antIcon} />;
      return <Com {...this.props}
        refId={refId}
      />
    }
  };
}
 
function randomId() {
  return Math.random().toString(36).substr(2, 12);
}