-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposts.ts
More file actions
28 lines (24 loc) · 1.04 KB
/
Copy pathposts.ts
File metadata and controls
28 lines (24 loc) · 1.04 KB
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
import { getCollection, type CollectionEntry } from 'astro:content';
export type Post = CollectionEntry<'posts'>;
/** All published posts, newest first. Drafts are hidden in production builds. */
export async function getPosts(): Promise<Post[]> {
const posts = await getCollection('posts', ({ data }) => import.meta.env.DEV || !data.draft);
return posts.sort((a, b) => b.data.date.getTime() - a.data.date.getTime());
}
/** Every tag in use, with its post count, alphabetically. */
export async function getTags(): Promise<{ tag: string; count: number }[]> {
const posts = await getPosts();
const counts = new Map<string, number>();
for (const post of posts) {
for (const tag of post.data.tags) {
counts.set(tag, (counts.get(tag) ?? 0) + 1);
}
}
return [...counts]
.map(([tag, count]) => ({ tag, count }))
.sort((a, b) => a.tag.localeCompare(b.tag));
}
/** Tags are used in URLs, so they travel lowercased and hyphenated. */
export function tagSlug(tag: string): string {
return tag.toLowerCase().replace(/\s+/g, '-');
}