-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposts.ts
More file actions
125 lines (111 loc) · 2.68 KB
/
posts.ts
File metadata and controls
125 lines (111 loc) · 2.68 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
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import { slugify } from "./util";
import { SupabaseClient } from "@supabase/supabase-js";
export interface DatabasePost {
id: string;
slug: string;
title: string;
description: string | null;
author: string;
content: string;
draft: boolean;
created_at: string;
updated_at: string;
date: string;
}
export interface BlogPostFrontmatter {
title: string;
date: string;
description: string;
author: string;
draft?: boolean;
}
export interface BlogPost {
slug: string;
frontmatter: BlogPostFrontmatter;
source?: "database" | "file";
}
export function convertDatabasePostToBlogPost(dbPost: DatabasePost): BlogPost {
return {
slug: dbPost.slug,
frontmatter: {
title: dbPost.title,
date: dbPost.date,
description: dbPost.description || "",
author: dbPost.author,
draft: dbPost.draft,
},
source: "database",
};
}
export async function getDatabasePosts(supabase: SupabaseClient): Promise<BlogPost[]> {
try {
const { data, error } = await supabase
.from("blog_posts")
.select("*")
.order("date", { ascending: false });
if (error) {
console.error("Error fetching database posts:", error);
return [];
}
return (data || []).map(convertDatabasePostToBlogPost);
} catch (error) {
console.error("Error fetching database posts:", error);
return [];
}
}
export async function getDatabasePostBySlug(
supabase: SupabaseClient,
slug: string
): Promise<DatabasePost | null> {
try {
const { data, error } = await supabase
.from("blog_posts")
.select("*")
.eq("slug", slug)
.single();
if (error || !data) {
return null;
}
return data;
} catch (error) {
console.error("Error fetching database post by slug:", error);
return null;
}
}
export async function createDatabasePost(
supabase: SupabaseClient,
post: {
title: string;
description?: string;
author: string;
content: string;
draft?: boolean;
date?: string;
slug?: string;
}): Promise<DatabasePost | null> {
try {
const slug = post.slug || slugify(post.title);
const date = post.date || new Date().toISOString();
const { data, error } = await supabase
.from("blog_posts")
.insert({
slug,
title: post.title,
description: post.description,
author: post.author,
content: post.content,
draft: post.draft || false,
date,
})
.select()
.single();
if (error) {
console.error("Error creating database post:", error);
return null;
}
return data;
} catch (error) {
console.error("Error creating database post:", error);
return null;
}
}