All files transform.js

90.32% Statements 28/31
68.18% Branches 15/22
100% Functions 9/9
90.32% Lines 28/31
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      3x               3x 106x 106x 61x 194x         61x 17x       106x   281x 281x       59x                       3x 43x 43x   43x 43x 43x     43x     3x 12x   12x   12x 12x   81x 15x     12x         12x        
import { visit } from 'graphql'
import { checkDocument, cloneDeep } from 'apollo-utilities'
 
const PERSIST_FIELD = {
  kind: 'Field',
  name: {
    kind: 'Name',
    value: '__persist'
  }
}
 
const addPersistFieldToSelectionSet = (selectionSet, isRoot = false) => {
  Eif (selectionSet.selections) {
    if (!isRoot) {
      const alreadyHasThisField = selectionSet.selections.some(selection => {
        return (
          selection.kind === 'Field' && selection.name.value === '__typename'
        )
      })
 
      if (!alreadyHasThisField) {
        selectionSet.selections.push(PERSIST_FIELD)
      }
    }
 
    selectionSet.selections.forEach(selection => {
      // Must not add __typename if we're inside an introspection query
      Eif (selection.kind === 'Field') {
        if (
          selection.name.value.lastIndexOf('__', 0) !== 0 &&
          selection.selectionSet
        ) {
          addPersistFieldToSelectionSet(selection.selectionSet)
        }
      }
      else if (selection.kind === 'InlineFragment') {
        if (selection.selectionSet) {
          addPersistFieldToSelectionSet(selection.selectionSet)
        }
      }
    })
  }
}
 
const addPersistFieldToDocument = doc => {
  checkDocument(doc)
  const docClone = cloneDeep(doc)
 
  docClone.definitions.forEach(definition => {
    const isRoot = definition.kind === 'OperationDefinition'
    addPersistFieldToSelectionSet(definition.selectionSet, isRoot)
  })
 
  return docClone
}
 
const extractPersistDirectivePaths = (originalQuery, directive = 'persist') => {
  let paths = []
 
  const query = visit(originalQuery, {
    Directive: ({ name: { value: name } }, key, parent, path, ancestors) => {
      Eif (name === directive) {
        paths.push(
          ancestors
            .filter(({ kind }) => kind === 'Field')
            .map(({ name: { value: name } }) => name)
        )
 
        return null
      }
    }
  })
 
  return { query, paths }
}
 
export { addPersistFieldToDocument, extractPersistDirectivePaths }