import { GetPublicApiCategoriesResponse, GetPublicApiPostsResponse, LatestPostsByLocale, PublicApiPostTranslation } from "../types"; import createPaths from "./createPaths"; import formatDate from "./formatDate"; import getUncategorizedCategoryProperties from "./getUncategorizedCategoryProperties"; type PostData = PublicApiPostTranslation & { slug: string; category: number; }; const sortPostTranslations = (posts: PostData[]) => { return posts.sort((a: PostData, b: PostData) => { const aDate = new Date(a.updatedAt); const bDate = new Date(b.updatedAt); if (aDate > bDate) return -1; return 1; }); }; const getLatestPostsByLocaleFromPostResponse = ( postsResponse: GetPublicApiPostsResponse, categoriesResponse: GetPublicApiCategoriesResponse, locales: string[] ): LatestPostsByLocale => { const responsePosts = postsResponse.data.items; const responseCategories = categoriesResponse.data.items; const latestPostsByLocale: LatestPostsByLocale = {}; locales.forEach(locale => { const postTranslations: PostData[] = []; responsePosts.forEach(post => { post.translations.forEach(translation => { if (translation.locale === locale) { postTranslations.push({ ...translation, slug: post.slug, category: post.category }); } }); }); const sortedPosts = sortPostTranslations(postTranslations); latestPostsByLocale[locale] = sortedPosts.map(post => { const category = responseCategories.find(category => category.id === post.category); return { translationId: post.id, title: post.title, description: post.metaDescription, updatedAt: formatDate(post.updatedAt, locale), link: `${createPaths.getPublicUrl()}/${createPaths.post( locale, !category ? getUncategorizedCategoryProperties(locale).slug : category.slug, post.slug )}` }; }); }); return latestPostsByLocale; }; export default getLatestPostsByLocaleFromPostResponse;