From 456cf011b36de91c9936994b1fa45703adcd309b Mon Sep 17 00:00:00 2001 From: Dawid Rycerz Date: Thu, 3 Jul 2025 10:56:21 +0300 Subject: Initial fork of chrismwilliams/astro-theme-cactus theme --- src/data/post.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/data/post.ts (limited to 'src/data/post.ts') diff --git a/src/data/post.ts b/src/data/post.ts new file mode 100644 index 0000000..87e0b01 --- /dev/null +++ b/src/data/post.ts @@ -0,0 +1,56 @@ +import { type CollectionEntry, getCollection } from "astro:content"; + +/** filter out draft posts based on the environment */ +export async function getAllPosts(): Promise[]> { + return await getCollection("post", ({ data }) => { + return import.meta.env.PROD ? !data.draft : true; + }); +} + +/** Get tag metadata by tag name */ +export async function getTagMeta(tag: string): Promise | undefined> { + const tagEntries = await getCollection("tag", (entry) => { + return entry.id === tag; + }); + return tagEntries[0]; +} + +/** groups posts by year (based on option siteConfig.sortPostsByUpdatedDate), using the year as the key + * Note: This function doesn't filter draft posts, pass it the result of getAllPosts above to do so. + */ +export function groupPostsByYear(posts: CollectionEntry<"post">[]) { + return posts.reduce[]>>((acc, post) => { + const year = post.data.publishDate.getFullYear(); + if (!acc[year]) { + acc[year] = []; + } + acc[year]?.push(post); + return acc; + }, {}); +} + +/** returns all tags created from posts (inc duplicate tags) + * Note: This function doesn't filter draft posts, pass it the result of getAllPosts above to do so. + * */ +export function getAllTags(posts: CollectionEntry<"post">[]) { + return posts.flatMap((post) => [...post.data.tags]); +} + +/** returns all unique tags created from posts + * Note: This function doesn't filter draft posts, pass it the result of getAllPosts above to do so. + * */ +export function getUniqueTags(posts: CollectionEntry<"post">[]) { + return [...new Set(getAllTags(posts))]; +} + +/** returns a count of each unique tag - [[tagName, count], ...] + * Note: This function doesn't filter draft posts, pass it the result of getAllPosts above to do so. + * */ +export function getUniqueTagsWithCount(posts: CollectionEntry<"post">[]): [string, number][] { + return [ + ...getAllTags(posts).reduce( + (acc, t) => acc.set(t, (acc.get(t) ?? 0) + 1), + new Map(), + ), + ].sort((a, b) => b[1] - a[1]); +} -- cgit v1.2.3