File size: 1,873 Bytes
d53e5b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { Request, Response } from 'express';
import prisma from '../models/prisma';

// GET /api/blog (Public)
export const getPublishedPosts = async (req: Request, res: Response) => {
    try {
        const posts = await prisma.blogPost.findMany({
            where: {
                status: 'PUBLISHED',
                publishedAt: {
                    lte: new Date(),
                },
            },
            orderBy: {
                publishedAt: 'desc',
            },
            include: {
                author: {
                    select: {
                        name: true,
                    },
                },
            },
        });

        return res.status(200).json(posts);
    } catch (error) {
        console.error('Error fetching blog posts:', error);
        return res.status(500).json({ error: 'Internal server error' });
    }
};

// GET /api/blog/:slug (Public)
export const getPostBySlug = async (req: Request, res: Response) => {
    try {
        const { slug } = req.params;

        const post = await prisma.blogPost.findFirst({
            where: {
                slug,
                status: 'PUBLISHED',
                publishedAt: {
                    lte: new Date(), // ensure it's not a scheduled post in the future
                },
            },
            include: {
                author: {
                    select: {
                        name: true,
                    },
                },
            },
        });

        if (!post) {
            return res.status(404).json({ error: 'Post not found' });
        }

        return res.status(200).json(post);
    } catch (error) {
        console.error('Error fetching blog post:', error);
        return res.status(500).json({ error: 'Internal server error' });
    }
};