graphql#visit JavaScript Examples

The following examples show how to use graphql#visit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From merkur with MIT License 5 votes vote down vote up
function addTypenameToSelections(document) {
  return visit(document, {
    SelectionSet: {
      enter(node, _key, parent) {
        // Don't add __typename to OperationDefinitions.
        if (parent && parent.kind === 'OperationDefinition') {
          return;
        }

        // No changes if no selections.
        const { selections } = node;
        if (!selections) {
          return;
        }

        // If selections already have a __typename, or are part of an
        // introspection query, do nothing.
        const skip = selections.some(
          (selection) =>
            selection.kind === 'Field' &&
            (selection.name.value === '__typename' ||
              selection.name.value.lastIndexOf('__', 0) === 0)
        );

        if (skip) {
          return;
        }

        // If this SelectionSet is @export-ed as an input variable, it should
        // not have a __typename field (see issue #4691).
        if (
          parent.kind === 'Field' &&
          parent.directives &&
          parent.directives.some((d) => d.name.value === 'export')
        ) {
          return;
        }

        // Create and return a new SelectionSet with a __typename Field.
        return Object.assign({}, node, {
          selections: [...selections, TYPENAME_FIELD],
        });
      },
    },
  });
}