summaryrefslogtreecommitdiffstats
path: root/src/services/graphql/articles.ts
blob: 1a7b2e05ddc89d5fa03e638cb5f5ca291f6694d2 (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { type Article, type ArticleCard, type Slug } from '@ts/types/app';
import { GraphQLEdgesInput, GraphQLPageInfo } from '@ts/types/graphql/generics';
import { EdgesResponse, EndCursorResponse } from '@ts/types/graphql/queries';
import {
  type RawArticle,
  type RawArticlePreview,
  type TotalItems,
} from '@ts/types/raw-data';
import { getAuthorFromRawData } from '@utils/helpers/author';
import { getImageFromRawData } from '@utils/helpers/images';
import { getPageLinkFromRawData } from '@utils/helpers/pages';
import { fetchAPI } from './api';
import {
  articleBySlugQuery,
  articlesCardQuery,
  articlesEndCursorQuery,
  articlesQuery,
  articlesSlugQuery,
  totalArticlesQuery,
} from './articles.query';

/**
 * Retrieve the total number of articles.
 *
 * @returns {Promise<number>} - The articles total number.
 */
export const getTotalArticles = async (search?: string): Promise<number> => {
  const response = await fetchAPI<TotalItems, typeof totalArticlesQuery>({
    query: totalArticlesQuery,
    variables: { search },
  });

  return response.posts.pageInfo.total;
};

export type GetArticlesReturn = {
  articles: Article[];
  pageInfo: GraphQLPageInfo;
};

/**
 * Convert raw data to an Article object.
 *
 * @param {RawArticle} data - The page raw data.
 * @returns {Article} The page data.
 */
export const getArticleFromRawData = (data: RawArticle): Article => {
  const {
    acfPosts,
    author,
    commentCount,
    contentParts,
    databaseId,
    date,
    featuredImage,
    info,
    modified,
    slug,
    title,
    seo,
  } = data;

  return {
    content: contentParts.afterMore,
    id: databaseId,
    intro: contentParts.beforeMore,
    meta: {
      author: author && getAuthorFromRawData(author.node, 'page'),
      commentsCount: commentCount || 0,
      cover: featuredImage?.node
        ? getImageFromRawData(featuredImage.node)
        : undefined,
      dates: { publication: date, update: modified },
      seo: {
        description: seo?.metaDesc || '',
        title: seo?.title || '',
      },
      thematics: acfPosts.postsInThematic?.map((thematic) =>
        getPageLinkFromRawData(thematic, 'thematic')
      ),
      topics: acfPosts.postsInTopic?.map((topic) =>
        getPageLinkFromRawData(topic, 'topic')
      ),
      wordsCount: info.wordsCount,
    },
    slug,
    title,
  };
};

/**
 * Retrieve the given number of articles from API.
 *
 * @param {GraphQLEdgesInput} props - An object of GraphQL variables.
 * @returns {Promise<EdgesResponse<RawArticle>>} The articles data.
 */
export const getArticles = async (
  props: GraphQLEdgesInput
): Promise<EdgesResponse<RawArticle>> => {
  const response = await fetchAPI<RawArticle, typeof articlesQuery>({
    query: articlesQuery,
    variables: { ...props },
  });

  return response.posts;
};

/**
 * Convert a raw article preview to an article card.
 *
 * @param {RawArticlePreview} data - A raw article preview.
 * @returns {ArticleCard} An article card.
 */
const getArticleCardFromRawData = (data: RawArticlePreview): ArticleCard => {
  const { databaseId, date, featuredImage, slug, title } = data;

  return {
    cover: featuredImage ? getImageFromRawData(featuredImage.node) : undefined,
    dates: { publication: date },
    id: databaseId,
    slug,
    title,
  };
};

/**
 * Retrieve the given number of article cards from API.
 *
 * @param {GraphQLEdgesInput} obj - An object.
 * @param {number} obj.first - The number of articles.
 * @returns {Promise<ArticleCard[]>} - The article cards data.
 */
export const getArticlesCard = async ({
  first,
}: GraphQLEdgesInput): Promise<ArticleCard[]> => {
  const response = await fetchAPI<RawArticlePreview, typeof articlesCardQuery>({
    query: articlesCardQuery,
    variables: { first },
  });

  return response.posts.nodes.map((node) => getArticleCardFromRawData(node));
};

/**
 * Retrieve an Article object by slug.
 *
 * @param {string} slug - The article slug.
 * @returns {Promise<Article>} The requested article.
 */
export const getArticleBySlug = async (slug: string): Promise<Article> => {
  const response = await fetchAPI<RawArticle, typeof articleBySlugQuery>({
    query: articleBySlugQuery,
    variables: { slug },
  });

  return getArticleFromRawData(response.post);
};

/**
 * Retrieve all the articles slugs.
 *
 * @returns {Promise<string[]>} - An array of articles slugs.
 */
export const getAllArticlesSlugs = async (): Promise<string[]> => {
  const totalArticles = await getTotalArticles();
  const response = await fetchAPI<Slug, typeof articlesSlugQuery>({
    query: articlesSlugQuery,
    variables: { first: totalArticles },
  });

  return response.posts.edges.map((edge) => edge.node.slug);
};

/**
 * Retrieve the last cursor.
 *
 * @param {GraphQLEdgesInput} props - An object of GraphQL variables.
 * @returns {Promise<string>} - The end cursor.
 */
export const getArticlesEndCursor = async (
  props: GraphQLEdgesInput
): Promise<string> => {
  const response = await fetchAPI<
    EndCursorResponse,
    typeof articlesEndCursorQuery
  >({
    query: articlesEndCursorQuery,
    variables: { ...props },
  });

  return response.posts.pageInfo.endCursor;
};