aboutsummaryrefslogtreecommitdiffstats
path: root/src/services/graphql/fetchers/posts/fetch-posts-list.ts
blob: 0bf6dc147213a3f6629dc7e67f989efe00849922 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
import type {
  GraphQLConnection,
  GraphQLEdgesInput,
  GraphQLPostOrderBy,
  GraphQLPostWhere,
  Nullable,
  WPPostPreview,
} from '../../../../types';
import { fetchGraphQL, getGraphQLUrl } from '../../../../utils/helpers';

export type PostsListResponse = {
  posts: Nullable<GraphQLConnection<WPPostPreview>>;
};

const postsListQuery = `query PostsList($after: String, $before: String, $first: Int, $last: Int, $authorName: String, $orderby: [PostObjectsConnectionOrderbyInput], $search: String, $title: String) {
  posts(
    after: $after
    before: $before
    first: $first
    last: $last
    where: {authorName: $authorName, orderby: $orderby, search: $search, title: $title}
  ) {
    edges {
      cursor
      node {
        acfPosts {
          postsInThematic {
            ... on Thematic {
              databaseId
              slug
              title
            }
          }
        }
        commentCount
        contentParts {
          beforeMore
        }
        databaseId
        date
        featuredImage {
          node {
            altText
            mediaDetails {
              height
              width
            }
            sourceUrl
            title
          }
        }
        info {
          wordsCount
        }
        modified
        slug
        title
      }
    }
    pageInfo {
      endCursor
      hasNextPage
      total
    }
  }
}`;

export type FetchPostsListInput = GraphQLEdgesInput & {
  orderBy?: GraphQLPostOrderBy;
  where?: GraphQLPostWhere;
};

/**
 * Retrieve a paginated list of WordPress posts.
 *
 * @param {FetchPostsListInput} input - The input to retrieve posts.
 * @returns {Promise<GraphQLConnection<WPPostPreview>>} The paginated posts.
 */
export const fetchPostsList = async ({
  orderBy,
  where,
  ...vars
}: FetchPostsListInput): Promise<GraphQLConnection<WPPostPreview>> => {
  const response = await fetchGraphQL<PostsListResponse>({
    query: postsListQuery,
    url: getGraphQLUrl(),
    variables: {
      ...vars,
      ...where,
      orderBy: orderBy ? [orderBy] : undefined,
    },
  });

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

  return response.posts;
};