aboutsummaryrefslogtreecommitdiffstats
path: root/src/services/graphql/fetchers/comments/fetch-comments.ts
blob: 85ae6c1c0b3a8ea8c67bdb620ee327b3873d51e0 (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
import type {
  GraphQLCommentWhere,
  GraphQLEdgesInput,
  GraphQLNodes,
  Nullable,
  WPComment,
} from '../../../../types';
import { fetchGraphQL, getGraphQLUrl } from '../../../../utils/helpers';

type CommentsListResponse = {
  comments: Nullable<GraphQLNodes<WPComment>>;
};

const commentsListQuery = `query CommentsList($first: Int, $contentId: ID, $contentName: String, $status: String) {
  comments(
    first: $first
    where: {contentId: $contentId, contentName: $contentName, order: ASC, orderby: COMMENT_DATE, status: $status}
  ) {
    nodes {
      approved
      author {
        node {
          avatar {
            height
            url
            width
          }
          name
          url
        }
      }
      content
      databaseId
      date
      parentDatabaseId
      status
    }
  }
}`;

export type FetchCommentsListInput = Pick<GraphQLEdgesInput, 'first'> & {
  where?: GraphQLCommentWhere;
};

/**
 * Retrieve the comments list.
 *
 * @param {FetchCommentsListInput} input - The input to retrieve comments.
 * @returns {Promise<WPComment[]>} An array of comments.
 */
export const fetchCommentsList = async ({
  where,
  ...vars
}: FetchCommentsListInput): Promise<WPComment[]> => {
  const response = await fetchGraphQL<CommentsListResponse>({
    query: commentsListQuery,
    url: getGraphQLUrl(),
    variables: { ...vars, ...where },
  });

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

  return response.comments.nodes;
};