<commit_before>import { graphql } from "react-apollo";
import gql from "graphql-tag";
import pluralize from "pluralize";
import { get, upperFirst, camelCase } from "lodash";
import React from "react";
import deepEqual from "deep-equal";
import compose from "lodash/fp/compose";
import generateFragmentWithFields from "../../utils/generateFragmentWithFields";

/**
 * withQuery
 * @param {gql fragment} fragment supply a fragment as the first argument
 * @param {options} options
 * @typedef {object} options
 * @property {boolean} isPlural Are we searching for 1 thing or many?
 * @property {string} queryName What the props come back on ( by default = modelName + 'Query')
 * @property {boolean} asFunction If true, this gives you back a function you can call directly instead of a HOC
 * @property {boolean} asQueryObj If true, this gives you back the gql query object aka gql`query myQuery () {}`
 * @property {string} idAs By default single record queries occur on an id. But, if the record doesn't have an id field, and instead has a 'code', you can set idAs: 'code'
 * @property {boolean} getIdFromParams Grab the id variable off the match.params object being passed in!
 * @property {boolean || string} showLoading Show a loading spinner over the whole component while the data is loading
 * @property {boolean} showError Default=true show an error message toastr if the an error occurs while loading the data
 * @return {props}: {xxxxQuery, data }
 */

export default function withQuery(inputFragment, options = {}) {
  const {
    isPlural,
    queryName,
    nameOverride,
    argsOverride,
    asFunction,
    asQueryObj,
    idAs,
    LoadingComp,
    client,
    variables,
    props,
    getIdFromParams,
    showLoading,
    inDialog,
    showError = true,
    options: queryOptions,
    ...rest
  } = options;
  let fragment = inputFragment;
  if (Array.isArray(fragment)) {
    fragment = generateFragmentWithFields(...fragment);
  }
  if (typeof fragment === "string" || typeof fragment !== "object") {
    throw new Error("Please provide a valid fragment when using withQuery!");
  }
  const name = get(fragment, "definitions[0].typeCondition.name.value");
  if (!name) {
    console.error("Bad fragment passed to withQuery!!");
    console.error(fragment, options);
    throw new Error(
      "No fragment name found in withQuery() call. This is due to passing in a string or something other than a gql fragment to withQuery"
    );
  }
  // const {fragment, extraMutateArgs} = options
  const fragName = fragment && fragment.definitions[0].name.value;
  const nameToUse = nameOverride || (isPlural ? pluralize(name) : name);
  const queryNameToUse = queryName || nameToUse + "Query";
  // const pascalNameToUse = pascalCase(nameToUse)
  let queryInner = `${fragName ? `...${fragName}` : idAs || "id"}`;
  if (isPlural) {
    queryInner = `results {
      ${queryInner}
    }
    totalResults`;
  }

  /* eslint-disable */
  let gqlQuery;
  if (argsOverride) {
    gqlQuery = gql`
    query ${queryNameToUse} ${argsOverride[0] || ""} {
      ${nameToUse} ${argsOverride[1] || ""} {
        ${queryInner}
      }
    }
    ${fragment ? fragment : ``}
  `;
  } else if (isPlural) {
    gqlQuery = gql`
      query ${queryNameToUse} ($pageSize: Int $sort: [String] $filter: JSON $pageNumber: Int) {
        ${nameToUse}(pageSize: $pageSize, sort: $sort, filter: $filter, pageNumber: $pageNumber) {
          ${queryInner}
        }
      }
      ${fragment ? fragment : ``}
    `;
  } else {
    gqlQuery = gql`
      query ${queryNameToUse} ($${idAs || "id"}: String!) {
        ${nameToUse}(${idAs || "id"}: $${idAs || "id"}) {
          ${queryInner}
        }
      }
      ${fragment ? fragment : ``}
    `;
  }

  /* eslint-enable */
  if (asQueryObj) {
    return gqlQuery;
  }
  if (asFunction) {
    if (!client)
      return console.error(
        "You need to pass the apollo client to withQuery if using as a function"
      );

    return function query(localVars) {
      return client
        .query({
          query: gqlQuery,
          name: "createDataFile",
          ssr: false,
          fetchPolicy: "network-only",
          ...queryOptions,
          variables:
            localVars ||
            variables ||
            (queryOptions && queryOptions.variables) ||
            undefined
        })
        .then(function(res) {
          return Promise.resolve(
            isPlural ? res.data[nameToUse].results : res.data[nameToUse],
            res.data,
            res
          );
        });
    };
  }

  return compose(
    graphql(gqlQuery, {
      //default options
      options: props => {
        const {
          variables: propVariables,
          fetchPolicy,
          pollInterval,
          notifyOnNetworkStatusChange
        } = props;
        if (getIdFromParams) {<commit_msg>add totalResults to withQuery as function<commit_after>import { graphql } from "react-apollo";
import gql from "graphql-tag";
import pluralize from "pluralize";
import { get, upperFirst, camelCase } from "lodash";
import React from "react";
import deepEqual from "deep-equal";
import compose from "lodash/fp/compose";
import generateFragmentWithFields from "../../utils/generateFragmentWithFields";

/**
 * withQuery
 * @param {gql fragment} fragment supply a fragment as the first argument
 * @param {options} options
 * @typedef {object} options
 * @property {boolean} isPlural Are we searching for 1 thing or many?
 * @property {string} queryName What the props come back on ( by default = modelName + 'Query')
 * @property {boolean} asFunction If true, this gives you back a function you can call directly instead of a HOC
 * @property {boolean} asQueryObj If true, this gives you back the gql query object aka gql`query myQuery () {}`
 * @property {string} idAs By default single record queries occur on an id. But, if the record doesn't have an id field, and instead has a 'code', you can set idAs: 'code'
 * @property {boolean} getIdFromParams Grab the id variable off the match.params object being passed in!
 * @property {boolean || string} showLoading Show a loading spinner over the whole component while the data is loading
 * @property {boolean} showError Default=true show an error message toastr if the an error occurs while loading the data
 * @return {props}: {xxxxQuery, data }
 */

export default function withQuery(inputFragment, options = {}) {
  const {
    isPlural,
    queryName,
    nameOverride,
    argsOverride,
    asFunction,
    asQueryObj,
    idAs,
    LoadingComp,
    client,
    variables,
    props,
    getIdFromParams,
    showLoading,
    inDialog,
    showError = true,
    options: queryOptions,
    ...rest
  } = options;
  let fragment = inputFragment;
  if (Array.isArray(fragment)) {
    fragment = generateFragmentWithFields(...fragment);
  }
  if (typeof fragment === "string" || typeof fragment !== "object") {
    throw new Error("Please provide a valid fragment when using withQuery!");
  }
  const name = get(fragment, "definitions[0].typeCondition.name.value");
  if (!name) {
    console.error("Bad fragment passed to withQuery!!");
    console.error(fragment, options);
    throw new Error(
      "No fragment name found in withQuery() call. This is due to passing in a string or something other than a gql fragment to withQuery"
    );
  }
  // const {fragment, extraMutateArgs} = options
  const fragName = fragment && fragment.definitions[0].name.value;
  const nameToUse = nameOverride || (isPlural ? pluralize(name) : name);
  const queryNameToUse = queryName || nameToUse + "Query";
  // const pascalNameToUse = pascalCase(nameToUse)
  let queryInner = `${fragName ? `...${fragName}` : idAs || "id"}`;
  if (isPlural) {
    queryInner = `results {
      ${queryInner}
    }
    totalResults`;
  }

  /* eslint-disable */
  let gqlQuery;
  if (argsOverride) {
    gqlQuery = gql`
    query ${queryNameToUse} ${argsOverride[0] || ""} {
      ${nameToUse} ${argsOverride[1] || ""} {
        ${queryInner}
      }
    }
    ${fragment ? fragment : ``}
  `;
  } else if (isPlural) {
    gqlQuery = gql`
      query ${queryNameToUse} ($pageSize: Int $sort: [String] $filter: JSON $pageNumber: Int) {
        ${nameToUse}(pageSize: $pageSize, sort: $sort, filter: $filter, pageNumber: $pageNumber) {
          ${queryInner}
        }
      }
      ${fragment ? fragment : ``}
    `;
  } else {
    gqlQuery = gql`
      query ${queryNameToUse} ($${idAs || "id"}: String!) {
        ${nameToUse}(${idAs || "id"}: $${idAs || "id"}) {
          ${queryInner}
        }
      }
      ${fragment ? fragment : ``}
    `;
  }

  /* eslint-enable */
  if (asQueryObj) {
    return gqlQuery;
  }
  if (asFunction) {
    if (!client)
      return console.error(
        "You need to pass the apollo client to withQuery if using as a function"
      );

    return function query(localVars) {
      return client
        .query({
          query: gqlQuery,
          name: "createDataFile",
          ssr: false,
          fetchPolicy: "network-only",
          ...queryOptions,
          variables:
            localVars ||
            variables ||
            (queryOptions && queryOptions.variables) ||
            undefined
        })
        .then(function(res) {
          const toReturn = isPlural
            ? [...res.data[nameToUse].results]
            : res.data[nameToUse];
          if (isPlural) {
            toReturn.totalResults = res.data[nameToUse].totalResults;
          }
          return toReturn;
        });
    };
  }

  return compose(
    graphql(gqlQuery, {
      //default options
      options: props => {
        const {
          variables: propVariables,
          fetchPolicy,
          pollInterval,
          notifyOnNetworkStatusChange
        } = props;
        if (getIdFromParams) {
{'fraction_non_alphanumeric': 0.11942123497045037, 'fraction_numerical': 0.0010189525168127166, 'mean_word_length': 2.7333586915176875, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3294980', 'n_tokens_mistral': 2874, 'n_tokens_neox': 2850, 'n_words': 899}