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

type LastPostCursorResponse = {
  posts: Nullable<{
    pageInfo: Pick<GraphQLPageInfo, 'endCursor'>;
  }>;
};

const lastPostCursorQuery = `query LastPostCursor($first: Int) {
  posts(first: $first) {
    pageInfo {
      endCursor
    }
  }
}`;

/**
 * Retrieve the cursor of the last post for a given number of posts.
 *
 * @param {number} count - The number of posts to fetch.
 * @returns {Promise<string>} The cursor of the last post.
 */
export const fetchLastPostCursor = async (count: number): Promise<string> => {
  const response = await fetchGraphQL<LastPostCursorResponse>({
    url: getGraphQLUrl(),
    query: lastPostCursorQuery,
    variables: { first: count },
  });

  if (!response.posts?.pageInfo.endCursor)
    return Promise.reject(
      new Error('Unable to find the cursor of the last post.')
    );

  return response.posts.pageInfo.endCursor;
};