diff options
| author | Armand Philippot <git@armandphilippot.com> | 2021-12-15 12:16:34 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2021-12-15 17:06:55 +0100 |
| commit | 0fa8ae55c52852c34c9143a6ec43c954c6404df1 (patch) | |
| tree | 32c5421025591386632c50200ce6bed3ce6e62b7 /src/services | |
| parent | 15d247cb0d52d9c091fa040fe1d9d45e9e506050 (diff) | |
chore: retrieve posts list on blog page
Diffstat (limited to 'src/services')
| -rw-r--r-- | src/services/graphql/blog.ts | 130 |
1 files changed, 130 insertions, 0 deletions
diff --git a/src/services/graphql/blog.ts b/src/services/graphql/blog.ts new file mode 100644 index 0000000..266af87 --- /dev/null +++ b/src/services/graphql/blog.ts @@ -0,0 +1,130 @@ +import { ArticlePreview } from '@ts/types/articles'; +import { + fetchPostsListReturn, + getPostsListReturn, + PostsListResponse, +} from '@ts/types/blog'; +import { gql } from 'graphql-request'; +import { getGraphQLClient } from './client'; + +export const fetchPublishedPosts: fetchPostsListReturn = async ( + first = 10, + after = '' +) => { + const client = getGraphQLClient(); + const query = gql` + query AllPublishedPosts($first: Int, $after: String) { + posts( + after: $after + first: $first + where: { status: PUBLISH, orderby: { field: DATE, order: DESC } } + ) { + edges { + cursor + node { + acfPosts { + postsInSubject { + ... on Subject { + databaseId + featuredImage { + node { + altText + sourceUrl + title + } + } + id + slug + title + } + } + postsInThematic { + ... on Thematic { + databaseId + id + slug + title + } + } + } + commentCount + contentParts { + beforeMore + } + date + featuredImage { + node { + altText + sourceUrl + title + } + } + id + databaseId + modified + slug + title + } + } + pageInfo { + endCursor + hasNextPage + } + } + } + `; + + const variables = { first, after }; + + try { + const response: PostsListResponse = await client.request(query, variables); + return response; + } catch (error) { + console.error(JSON.stringify(error, undefined, 2)); + process.exit(1); + } +}; + +export const getPublishedPosts: getPostsListReturn = async ( + first = 10, + after = '' +) => { + const rawPostsList = await fetchPublishedPosts(first, after); + const postsList: ArticlePreview[] = rawPostsList.posts.edges.map((post) => { + const { + acfPosts, + commentCount, + contentParts, + databaseId, + date, + id, + modified, + slug, + title, + } = post.node; + const content = contentParts.beforeMore; + const dates = { publication: date, update: modified }; + const subjects = + acfPosts.postsInSubject && acfPosts.postsInSubject?.length > 0 + ? acfPosts.postsInSubject + : []; + const thematics = + acfPosts.postsInThematics && acfPosts.postsInThematics?.length > 0 + ? acfPosts.postsInThematics + : []; + + return { + commentCount, + content, + databaseId, + date: dates, + id, + slug, + subjects, + thematics, + title, + }; + }); + + return { posts: postsList, pageInfo: rawPostsList.posts.pageInfo }; +}; |
