All files / src hoc-utils.tsx

92.86% Statements 39/42
86.67% Branches 13/15
88.89% Functions 8/9
100% Lines 32/32
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 7927x 27x     27x   124x 27x 155x   27x 193x     27x           53x 53x 53x   53x 53x   53x 49x 49x       4x 3x 3x     1x 1x             52x           27x                 174x 174x     27x 2x         2x     27x 2x   27x  
import * as React from 'react';
const invariant = require('invariant');
 
import { OperationVariables } from './types';
import { DocumentType, IDocumentDefinition } from './parser';
 
export const defaultMapPropsToOptions = () => ({});
export const defaultMapResultToProps: <P>(props: P) => P = props => props;
export const defaultMapPropsToSkip = () => false;
 
export function getDisplayName<P>(WrappedComponent: React.ComponentType<P>) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
 
export function calculateVariablesFromProps<TProps>(
  operation: IDocumentDefinition,
  props: TProps,
  graphQLDisplayName: string,
  wrapperName: string,
) {
  let variables: OperationVariables = {};
  for (let { variable, type } of operation.variables) {
    Iif (!variable.name || !variable.name.value) continue;
 
    const variableName = variable.name.value;
    const variableProp = (props as any)[variableName];
 
    if (typeof variableProp !== 'undefined') {
      variables[variableName] = variableProp;
      continue;
    }
 
    // allow optional props
    if (type.kind !== 'NonNullType') {
      variables[variableName] = null;
      continue;
    }
 
    Iif (operation.type === DocumentType.Mutation) return;
    invariant(
      typeof variableProp !== 'undefined',
      `The operation '${operation.name}' wrapping '${wrapperName}' ` +
        `is expecting a variable: '${variable.name.value}' but it was not found in the props ` +
        `passed to '${graphQLDisplayName}'`,
    );
  }
  return variables;
}
 
export type RefSetter<TChildProps> = (ref: React.ComponentClass<TChildProps>) => void | void;
 
// base class for hocs to easily manage refs
export class GraphQLBase<TProps, TChildProps, TState = any> extends React.Component<
  TProps,
  TState
> {
  public withRef: boolean;
  // wrapped instance
  private wrappedInstance: React.ComponentClass<TChildProps>;
 
  constructor(props: TProps) {
    super(props);
    this.setWrappedInstance = this.setWrappedInstance.bind(this);
  }
 
  getWrappedInstance() {
    invariant(
      this.withRef,
      `To access the wrapped instance, you need to specify ` + `{ withRef: true } in the options`,
    );
 
    return this.wrappedInstance;
  }
 
  setWrappedInstance(ref: React.ComponentClass<TChildProps>) {
    this.wrappedInstance = ref;
  }
}