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

export type RecentPostsResponse = {
  posts: Nullable<GraphQLConnection<RecentWPPost>>;
};

const recentPostsQuery = `query RecentPosts($after: String, $before: String, $first: Int, $last: Int, $authorName: String, $search: String, $title: String) {
  posts(
    after: $after
    before: $before
    first: $first
    last: $last
    where: {authorName: $authorName, search: $search, title: $title, orderby: {field: DATE, order: DESC}}
  ) {
    edges {
      cursor
      node {
        databaseId
        date
        featuredImage {
          node {
            altText
            mediaDetails {
              height
              width
            }
            sourceUrl
            title
          }
        }
        slug
        title
      }
    }
    pageInfo {
      endCursor
      hasNextPage
      hasPreviousPage
      startCursor
      total
    }
  }
}`;

export type FetchRecentPostsInput = GraphQLEdgesInput & {
  where?: GraphQLPostWhere;
};

/**
 * Retrieve a paginated list of recent WordPress posts.
 *
 * @param {FetchRecentPostsInput} input - The input to retrieve recent posts.
 * @returns {Promise<GraphQLConnection<RecentWPPost>>} The recent posts.
 */
export const fetchRecentPosts = async ({
  where,
  ...vars
}: FetchRecentPostsInput): Promise<GraphQLConnection<RecentWPPost>> => {
  const response = await fetchGraphQL<RecentPostsResponse>({
    query: recentPostsQuery,
    url: getGraphQLUrl(),
    variables: { ...vars, ...where },
  });

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

  return response.posts;
};