summaryrefslogtreecommitdiff
path: root/src/lib/utils/posts.ts
blob: cc05c838bf5128bbd3e42eb4603e36cd3d759eb7 (plain)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import type { Component } from 'svelte';

export interface PostMetadata {
    title: string;
    date: string;
    description: string;
    tags?: string[];
}

export interface Post extends PostMetadata {
    slug: string;
}

export interface PostModule {
    default: Component;
    metadata: PostMetadata;
}

// Use Vite's glob import to get all .svx files from posts directory
const postFiles = import.meta.glob<PostModule>('/src/posts/*.svx', { eager: true });

/**
 * Get all posts, sorted by date (newest first)
 */
export function getPosts(): Post[] {
    const posts: Post[] = [];

    for (const path in postFiles) {
        const file = postFiles[path];
        // Extract slug from path: /src/posts/hello-world.svx -> hello-world
        const slug = path.split('/').pop()?.replace('.svx', '') ?? '';

        if (file.metadata) {
            posts.push({
                ...file.metadata,
                slug
            });
        }
    }

    // Sort by date, newest first
    return posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
}

/**
 * Get a single post by slug
 */
export function getPost(slug: string): PostModule | undefined {
    const path = `/src/posts/${slug}.svx`;
    return postFiles[path];
}