aboutsummaryrefslogtreecommitdiffstats
path: root/src/services/graphql/fetchers/topics/fetch-topics-count.ts
blob: 0f8bdfcf3a3401acb930951c1d42eb3f266940f8 (plain)
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
import type {
  GraphQLPageInfo,
  GraphQLTaxonomyWhere,
  Nullable,
} from '../../../../types';
import { fetchGraphQL, getGraphQLUrl } from '../../../../utils/helpers';

export type TopicsCountResponse = {
  topics: Nullable<{
    pageInfo: Pick<GraphQLPageInfo, 'total'>;
  }>;
};

const topicsCountQuery = `query TopicsCount($search: String, $title: String) {
  topics(where: {search: $search, title: $title}) {
    pageInfo {
      total
    }
  }
}`;

/**
 * Retrieve the total of WordPress topics.
 *
 * @param {GraphQLTaxonomyWhere} [input] - The input to filter the topics.
 * @returns {Promise<number>} The total number of topics.
 */
export const fetchTopicsCount = async (
  input?: GraphQLTaxonomyWhere
): Promise<number> => {
  const response = await fetchGraphQL<TopicsCountResponse>({
    query: topicsCountQuery,
    url: getGraphQLUrl(),
    variables: { ...input },
  });

  if (!response.topics)
    return Promise.reject(
      new Error('Unable to find the total number of topics.')
    );

  return response.topics.pageInfo.total;
};