blog.hangerthem.com/lib/categories.ts

43 lines
1.4 KiB
TypeScript

import { findSlugInArray } from '@/utils/slug'
import { getAllPostsMeta } from '@/lib/posts'
/**
* Retrieves all unique categories from the posts and counts the number of posts in each category.
* @returns An object where keys are category names and values are the count of posts in that category.
*/
export function getAllCategories(): Record<string, number> {
const posts = getAllPostsMeta()
const categories = {} as Record<string, number>
posts.forEach((post) => {
const category = post.category
categories[category] = (categories[category] || 0) + 1
})
return categories
}
/** * Finds a category by its slug.
* @param categorySlug - The slug of the category to find.
* @returns The original category name if found, otherwise null.
*/
export function getCategoryBySlug(categorySlug: string): string | null {
const categories = getAllCategories()
return findSlugInArray(categorySlug, Object.keys(categories))
}
/**
* Retrieves all posts that belong to a specific category.
* @param categorySlug - The slug of the category to filter posts by.
* @returns An array of posts that belong to the specified category.
*/
export function getPostsByCategory(categorySlug: string) {
const categories = getAllCategories()
const category = findSlugInArray(categorySlug, Object.keys(categories))
if (!category) {
return []
}
return getAllPostsMeta().filter((post) => post.category === category)
}