All files / src/hocs relation.js

10% Statements 6/60
5.56% Branches 2/36
13.33% Functions 2/15
8.77% Lines 5/57

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                                                                                                                                                                                                                                                                                                              2x 2x 1x   3x     2x                                
// @flow
 
import * as React from 'react';
import {Spin, Icon} from 'antd';
import RefId from 'canner-ref-id';
import Toolbar from './components/toolbar';
import {mapValues} from 'lodash';
import type {HOCProps} from './types';
import {parseConnectionToNormal, getValue, defaultValue} from './utils';
import {withApollo} from 'react-apollo';
import gql from 'graphql-tag';
import {Query} from '../query';
import {List} from 'react-content-loader';
 
type State = {
  originRootValue: any,
  isFetching: boolean,
  current: number
}
 
type Props = HOCProps & {
  client: any
}
 
@withApollo
export default function withQuery(Com: React.ComponentType<*>) {
  // this hoc will fetch data;
  return class ComponentWithQuery extends React.PureComponent<Props, State> {
    query: Query;
 
    constructor(props: Props) {
      super(props);
      this.state = {
        originRootValue: null,
        isFetching: true,
        current: 0
      };
      if (props.relation) {
        this.query = new Query({schema: props.schema});
      }
    }
 
    componentDidMount() {
      const {relation, toolbar} = this.props;
      if (!relation) {
        return;
      }
      let args = this.getArgs();
      if (toolbar && toolbar.async) {
        args = {...args, first: 10}
      }
      if (!toolbar || !toolbar.async) {
        args.first = undefined;
        delete args.last;
        delete args.after;
        delete args.before;
      }
      if (toolbar && toolbar.async && toolbar.filter && toolbar.filter.permanentFilter) {
        args = {...args, where: toolbar.filter.permanentFilter};
      }
      // this method will also query data
      this.updateQuery([relation.to], args);
    }
 
    UNSAFE_componentWillReceiveProps(props: Props) {
      const {refId, relation} = this.props;
      if (!relation) {
        return;
      }
      if (refId.toString() !== props.refId.toString()) {
        // refetch when route change
        this.queryData(props);
      }
    }
 
    queryData = (props?: Props): Promise<*> => {
      const {relation, client} = props || this.props;
      if (!relation) {
        return Promise.resolve();
      }
      this.setState({
        isFetching: true,
      });
      const gqlStr = this.query.toGQL(relation.to);
      const variables = this.query.getVairables();
      return client.query({
        query: gql`${gqlStr}`,
        variables
      }).then(({data}) => {
          this.setState({
            originRootValue: data,
            isFetching: false,
          });
        })
        .catch(() => {
          this.setState({
            isFetching: false
          })
        });
    }
 
    getArgs = () => {
      const {relation} = this.props;
      const queries = this.query.getQueries([relation.to]).args || {pagination: {first: 10}};
      const variables = this.query.getVairables();
      const args = mapValues(queries, v => variables[v.substr(1)]);
      return args;
    }
 
    updateQuery = (paths: Array<string>, args: Object) => {
      this.query.updateQueries(paths, 'args', args);
      this.queryData();
    }
 
    render() {
      let {originRootValue, isFetching} = this.state;
      const {toolbar, relation, schema, refId} = this.props;
      if (!relation) {
        return <Com {...this.props}/>;
      }
      if (!originRootValue) {
        return <List style={{maxWidth: 500}} />;
      }
      const args = this.getArgs();
      const removeSelfRootValue = {[relation.to]: removeSelf(originRootValue[relation.to], refId, relation.to)};
      let parsedRootValue = removeSelfRootValue;
      const tb = ({children, ...restProps}) => <Toolbar
        {...restProps}
        items={schema[relation.to].items.items}
        toolbar={toolbar || {pagination: {type: 'pagination'}}}
        args={args}
        query={this.query}
        keyName={relation.to}
        refId={new RefId(relation.to)}
        originRootValue={parsedRootValue}
        updateQuery={this.updateQuery}
        parseConnectionToNormal={parseConnectionToNormal}
        getValue={getValue}
        defaultValue={defaultValue}
      >
        {/* $FlowFixMe */}
        <SpinWrapper isFetching={isFetching}>
          {children}
        </SpinWrapper>
      </Toolbar>;
      return <Com {...this.props} Toolbar={tb} relationValue={removeSelfRootValue[relation.to]}/>;
    }
  };
}
 
export function removeSelf(value: any, refId: RefId, relationTo: string) {
  const [key, index] = refId.getPathArr().slice(0, 2);
  if (key !== relationTo) {
    return value;
  }
  return {...value, edges: value.edges.filter((v, i) => i !== Number(index))};
}
 
const antIcon = <Icon type="loading" style={{fontSize: 24}} spin />;
 
function SpinWrapper({
  isFetching,
  children,
  value
}: {
  isFetching: boolean,
  children: Function,
  value: any
}): React.Element<*> {
  return (
    <Spin indicator={antIcon} spinning={isFetching}>
      {children(value)}
    </Spin>
  )
}