All files validation.js

80.43% Statements 37/46
79.55% Branches 35/44
90% Functions 9/10
80% Lines 36/45

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                            10x                   10x 10x   3x   7x 7x       2x       6x   6x 6x 6x     6x 6x     6x 6x 6x   6x   6x 2x       2x       4x             4x       4x               2x 2x 1x           16x 16x                                                       6x 12x 12x 12x 12x       12x 12x           12x                
// @flow
 
import * as React from 'react';
import RefId from 'canner-ref-id';
import Ajv from 'ajv';
import {isEmpty, isArray, isPlainObject, get} from 'lodash';
import type {HOCProps} from './types';
 
type State = {
  error: boolean,
  errorInfo: Array<any>
}
 
export default function withValidation(Com: React.ComponentType<*>) {
  return class ComponentWithValition extends React.Component<HOCProps, State> {
    key: string;
    id: ?string;
    callbackId: ?string;
    state = {
      error: false,
      errorInfo: []
    }
 
    componentDidMount() {
      const {refId, validation = {}, onDeploy, required = false} = this.props;
      if (isEmpty(validation) && !required) {
        // no validation
        return;
      }
      const key = refId.getPathArr()[0];
      this.callbackId = onDeploy(key, this.validate);
    }
 
    componentWillUnmount() {
      this.removeOnDeploy();
    }
 
    validate = (result: any) => {
      const {refId, validation = {}, required = false} = this.props;
      // required
      const paths = refId.getPathArr().slice(1);
      const {value} = getValueAndPaths(result.data, paths);
      const isRequiredValid = required ? Boolean(value) : true;
 
      // Ajv validation
      const ajv = new Ajv();
      const validate = ajv.compile(validation);
      
      // custom validator
      const {validator, errorMessage} = validation;
      const reject = message => ({error: true, message});
      const validatorResult = validator && validator(value, reject);
  
      let customValid = !(validatorResult && validatorResult.error);
      // if value is empty, should not validate with ajv
      if (customValid && isRequiredValid && (!value || validate(value))) {
        this.setState({
          error: false,
          errorInfo: []
        });
        return result;
      }
      
  
      const errorInfo = []
        .concat(isRequiredValid ? [] : {
          message: 'should be required'
        })
        .concat(validate.errors ? (errorMessage ? {message: errorMessage} : validate.errors) : [])
        .concat(customValid ? [] : validatorResult);
 
      this.setState({
        error: true,
        errorInfo: errorInfo
      });
      return {
        ...result,
        error: true,
        errorInfo: errorInfo
      }
    }
 
    removeOnDeploy = () => {
      const {refId, removeOnDeploy} = this.props;
      if (this.callbackId) {
        removeOnDeploy(refId.getPathArr()[0], this.callbackId || '');
      }
    }
    
 
    render() {
      const {error, errorInfo} = this.state;
      return <React.Fragment>
        <Com {...this.props} error={error} errorInfo={errorInfo || []}/>
      </React.Fragment>
  }
  };
}
 
export function splitRefId({
  refId,
  rootValue,
  pattern
}: {
  refId: RefId,
  rootValue: any,
  pattern: string
}) {
  const [key, index] = refId.getPathArr();
  let id;
  if (pattern.startsWith('array')) {
    id = get(rootValue, [key, index, 'id']);
  }
  return {
    key,
    id
  }
}
 
export function getValueAndPaths(value: Object, idPathArr: Array<string>) {
  return idPathArr.reduce((result: any, key: string) => {
    let v = result.value;
    let paths = result.paths;
    Eif (isPlainObject(v)) {
      Iif ('edges' in v && 'pageInfo' in v) {
        v = get(v, ['edges', key, 'node']);
        paths = paths.concat(['edges', key, 'node']);
      } else {
        v = v[key];
        paths = paths.concat(key);
      }
    } else if (isArray(v)) {
      v = v[key];
      paths = paths.concat(key);
    }
    return {
      value: v,
      paths
    }
  }, {
    value,
    paths: []
  });
}