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

export type LastPostCursorResponse = {
  posts: Nullable<Record<'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;
};