aboutsummaryrefslogtreecommitdiffstats
path: root/src/services/graphql/fetchers/topics/fetch-topics-list.ts
blob: 6f2ab8f3aa04cfdb2c9bed607ffbf4e2d649effc (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
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
79
80
81
82
83
84
import type {
  GraphQLConnection,
  GraphQLEdgesInput,
  GraphQLTaxonomyOrderBy,
  GraphQLTaxonomyWhere,
  Nullable,
  WPTopicPreview,
} from '../../../../types';
import { fetchGraphQL, getGraphQLUrl } from '../../../../utils/helpers';

export type TopicsListResponse = {
  topics: Nullable<GraphQLConnection<WPTopicPreview>>;
};

const topicsListQuery = `query TopicsList($after: String, $before: String, $first: Int, $last: Int, $orderby: [PostObjectsConnectionOrderbyInput], $search: String, $title: String, $notIn: [ID]) {
  topics(
    after: $after
    before: $before
    first: $first
    last: $last
    where: {orderby: $orderby, search: $search, title: $title, notIn: $notIn}
  ) {
    edges {
      cursor
      node {
        contentParts {
          beforeMore
        }
        databaseId
        featuredImage {
          node {
            altText
            mediaDetails {
              height
              width
            }
            sourceUrl
            title
          }
        }
        slug
        title
      }
    }
    pageInfo {
      endCursor
      hasNextPage
      hasPreviousPage
      startCursor
      total
    }
  }
}`;

export type FetchTopicsListInput = GraphQLEdgesInput & {
  orderBy?: GraphQLTaxonomyOrderBy;
  where?: GraphQLTaxonomyWhere;
};

/**
 * Retrieve a paginated list of WordPress topics.
 *
 * @param {FetchTopicsListInput} input - The input to retrieve topics.
 * @returns {Promise<GraphQLConnection<WPTopicPreview>>} The paginated topics.
 */
export const fetchTopicsList = async ({
  orderBy,
  where,
  ...vars
}: FetchTopicsListInput): Promise<GraphQLConnection<WPTopicPreview>> => {
  const response = await fetchGraphQL<TopicsListResponse>({
    query: topicsListQuery,
    url: getGraphQLUrl(),
    variables: {
      ...vars,
      ...where,
      orderBy: orderBy ? [orderBy] : undefined,
    },
  });

  if (!response.topics) return Promise.reject(new Error('No topics found.'));

  return response.topics;
};