Chrysoblog/src/lib/posts.ts

55 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-10-11 01:25:09 -07:00
import type { Post } from '$lib/types'
type PostMetadata = {
title: string ,
description?: string,
tags: [string],
series?: [string],
date: Date,
}
export function transformPostMeta(metadata: PostMetadata, slug: string) : Post {
return {
...metadata,
date: new Date(metadata.date),
slug,
};
}
export async function getPosts(tag: string | null = null) : Promise<Post[]> {
2024-09-29 16:40:26 -07:00
const allPostFiles = import.meta.glob('$content/post/*.md');
const iterablePostFiles = Object.entries(allPostFiles);
2024-10-11 01:25:09 -07:00
let posts: Post[] = await Promise.all(
2024-09-29 16:40:26 -07:00
iterablePostFiles.map(async ([pathMarkdown, resolver]) => {
const { metadata } = await resolver();
2024-10-11 01:25:09 -07:00
const slug = pathMarkdown.slice(pathMarkdown.lastIndexOf("/") + 1, -".md".length);
2024-09-29 16:40:26 -07:00
2024-10-11 01:25:09 -07:00
return transformPostMeta(metadata, slug);
2024-09-29 16:40:26 -07:00
})
);
2024-10-10 12:00:35 -07:00
if (tag)
2024-10-11 01:25:09 -07:00
posts = posts.filter(post => post.tags.includes(tag))
2024-09-29 16:40:26 -07:00
2024-10-10 12:00:35 -07:00
posts.sort((post1, post2) => {
2024-10-11 01:25:09 -07:00
const date1: Date = post1.date;
const date2: Date = post2.date;
2024-09-29 16:40:26 -07:00
return date2.getTime() - date1.getTime();
});
2024-10-10 12:00:35 -07:00
return posts;
}
2024-10-10 15:20:28 -07:00
export async function getTags() : Promise<Map<string, number>> {
2024-10-10 12:00:35 -07:00
const allPostFiles = import.meta.glob('$content/post/*.md');
const iterablePostFiles = Object.entries(allPostFiles);
const allPosts: string[][] = await Promise.all(
iterablePostFiles.map(async ([_, resolver]) => {
const { metadata } = await resolver();
return metadata.tags;
})
);
2024-10-10 15:20:28 -07:00
return allPosts.flat().reduce((acc: Map<string, number>, curr: string) => {
return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc
}, new Map());
2024-09-29 16:40:26 -07:00
}