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

export type PostResponse = {
  post: Nullable<WPPost>;
};

const postQuery = `query Post($slug: ID!) {
  post(id: $slug, idType: SLUG) {
    acfPosts {
      postsInThematic {
        ... on Thematic {
          databaseId
          slug
          title
        }
      }
      postsInTopic {
        ... on Topic {
          databaseId
          featuredImage {
            node {
              altText
              mediaDetails {
                height
                width
              }
              sourceUrl
              title
            }
          }
          slug
          title
        }
      }
    }
    author {
      node {
        name
      }
    }
    commentCount
    contentParts {
      afterMore
      beforeMore
    }
    databaseId
    date
    featuredImage {
      node {
        altText
        mediaDetails {
          height
          width
        }
        sourceUrl
        title
      }
    }
    info {
      wordsCount
    }
    modified
    seo {
      metaDesc
      title
    }
    slug
    title
  }
}`;

/**
 * Retrieve a WordPress post by slug.
 *
 * @param {string} slug - The post slug.
 * @returns {Promise<WPPost>} The requested post.
 */
export const fetchPost = async (slug: string): Promise<WPPost> => {
  const response = await fetchGraphQL<PostResponse>({
    query: postQuery,
    url: getGraphQLUrl(),
    variables: { slug },
  });

  if (!response.post)
    return Promise.reject(
      new Error(`No post found for the following slug ${slug}.`)
    );

  return response.post;
};