All files / src/query/schema relationField.js

50% Statements 10/20
26.67% Branches 4/15
45.45% Functions 5/11
50% Lines 10/20

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                                  64x 64x 64x 64x               31x       64x                                                                 31x             31x 153x 153x        
// @flow
 
import forEach from 'lodash/forEach';
import {types} from './types';
import {createField, capitalizeFirstLetter} from './utils';
import NullField from './nullField';
import * as pluralize from 'pluralize';
 
import type {Field} from './types';
 
export default class RelationField implements Field {
  schema: any;
  key: string;
  relationSchema: any;
  rootSchema: any;
 
  constructor({rootSchema, schema, key}: {rootSchema: any, schema: any, key: string}) {
    this.key = key;
    this.schema = schema;
    this.rootSchema = rootSchema;
    this.relationSchema = rootSchema[this.schema.relation.to];
  }
 
  exists() {
    return true;
  }
 
  getKey() {
    return this.key;
  }
 
  getType() {
    return types.RELATION;
  }
 
  isToOne() {
    return (this.schema.relation && this.schema.relation.type === 'toOne');
  }
 
  isToMany() {
    return (this.schema.relation && this.schema.relation.type === 'toMany');
  }
 
  relationTo() {
    return this.schema.relation.to;
  }
 
  getTypename() {
    return capitalizeFirstLetter(pluralize.singular(this.relationTo()));
  }
 
  getChild(fieldName: string) {
    if (!this.relationSchema ||
      !this.relationSchema.items ||
      !this.relationSchema.items.items ||
      !this.relationSchema.items.items[fieldName]
    ) {
      return new NullField({key: fieldName});
    }
 
    const field = createField(fieldName, this.rootSchema, this.relationSchema.items.items[fieldName]);
    return field;
  }
 
  forEach(visitor: Function) {
    Iif (!this.relationSchema ||
      !this.relationSchema.items ||
      !this.relationSchema.items.items
    ) {
      return;
    }
 
    forEach(this.relationSchema.items.items, (item, key) => {
      const field = createField(key, this.rootSchema, this.relationSchema.items.items[key]);
      visitor(field);
    });
  }
}