aboutsummaryrefslogtreecommitdiffstats
path: root/src/services/graphql/fetchers/posts/fetch-posts-count.ts
blob: 316cd475003157604819f2240ba155b62ccc078f (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
import type {
  GraphQLPageInfo,
  GraphQLPostWhere,
  Nullable,
} from '../../../../types';
import { fetchGraphQL, getGraphQLUrl } from '../../../../utils/helpers';

export type PostsCountResponse = {
  posts: Nullable<Record<'pageInfo', Pick<GraphQLPageInfo, 'total'>>>;
};

const postsCountQuery = `query PostsCount($authorName: String, $search: String, $title: String) {
  posts(where: {authorName: $authorName, search: $search, title: $title}) {
    pageInfo {
      total
    }
  }
}`;

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

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

  return response.posts.pageInfo.total;
};