Repository navigation
Expand file tree
/
Copy pathposts.ts
More file actions
237 lines (216 loc) · 6.84 KB
/
Copy pathposts.ts
File metadata and controls
237 lines (216 loc) · 6.84 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { db } from "@/server/db/index";
import * as Sentry from "@sentry/nextjs";
import "server-only";
import { z } from "zod";
import { posts, user, feed_sources, post_tags, tag } from "../db/schema";
import { eq, and, isNotNull, lte, desc, sql } from "drizzle-orm";
export const GetPreviewSchema = z.object({
id: z.string(),
});
type GetPreview = z.infer<typeof GetPreviewSchema>;
export async function getPostPreview({ id }: GetPreview) {
try {
GetPreviewSchema.parse({ id });
// Use direct query with join instead of ORM relations
const result = await db
.select({
id: posts.id,
title: posts.title,
body: posts.body,
publishedAt: posts.publishedAt,
updatedAt: posts.updatedAt,
readingTime: posts.readingTime,
slug: posts.slug,
excerpt: posts.excerpt,
canonicalUrl: posts.canonicalUrl,
showComments: posts.showComments,
userName: user.name,
userImage: user.image,
userUsername: user.username,
userBio: user.bio,
userId: user.id,
})
.from(posts)
.leftJoin(user, eq(posts.authorId, user.id))
.where(eq(posts.id, id))
.limit(1);
if (result.length === 0) {
return null;
}
const postData = result[0];
// Get tags separately
const postTags = await db
.select({
id: post_tags.id,
tagTitle: tag.title,
})
.from(post_tags)
.innerJoin(tag, eq(post_tags.tagId, tag.id))
.where(eq(post_tags.postId, id));
// Map to expected format for backward compatibility
return {
id: postData.id,
title: postData.title,
body: postData.body,
published: postData.publishedAt,
updatedAt: postData.updatedAt,
readTimeMins: postData.readingTime,
slug: postData.slug,
excerpt: postData.excerpt,
canonicalUrl: postData.canonicalUrl,
showComments: postData.showComments,
user: {
id: postData.userId,
name: postData.userName,
image: postData.userImage,
username: postData.userUsername,
bio: postData.userBio,
},
tags: postTags.map((pt) => ({ id: pt.id, tag: { title: pt.tagTitle } })),
};
} catch (error) {
console.error("getPostPreview error:", error);
Sentry.captureException(error);
throw new Error("Error fetching post");
}
}
export type TrendingItem = {
type: "post" | "feed";
id: string | number;
slug: string;
title: string;
excerpt: string | null;
publishedAt: string | null;
readTimeMins: number;
upvotes: number;
downvotes: number;
score: number;
// For posts (user articles)
username?: string;
authorName?: string | null;
authorImage?: string | null;
// For feed articles
sourceSlug?: string;
sourceName?: string | null;
sourceImage?: string | null;
externalUrl?: string | null;
imageUrl?: string | null;
isBookmarked?: boolean;
};
export const GetUnifiedTrendingSchema = z.object({
currentUserId: z.string().optional(),
limit: z.number().min(1).max(30).default(8),
});
type GetUnifiedTrending = z.infer<typeof GetUnifiedTrendingSchema>;
export async function getUnifiedTrending({
currentUserId,
limit = 8,
}: GetUnifiedTrending): Promise<TrendingItem[] | null> {
try {
GetUnifiedTrendingSchema.parse({ currentUserId, limit });
// Get trending user posts (using new posts table with type: "article")
const userPostsQuery = db
.select({
id: posts.id,
slug: posts.slug,
title: posts.title,
excerpt: posts.excerpt,
publishedAt: posts.publishedAt,
readTimeMins: posts.readingTime,
upvotes: posts.upvotesCount,
downvotes: posts.downvotesCount,
username: user.username,
authorName: user.name,
authorImage: user.image,
})
.from(posts)
.leftJoin(user, eq(posts.authorId, user.id))
.where(
and(
eq(posts.type, "article"),
eq(posts.status, "published"),
isNotNull(posts.publishedAt),
lte(posts.publishedAt, new Date().toISOString()),
),
)
.orderBy(desc(sql`(${posts.upvotesCount} - ${posts.downvotesCount})`))
.limit(limit);
// Get trending feed articles (using new posts table with type: "link")
const feedQuery = db
.select({
id: posts.id,
slug: posts.slug,
title: posts.title,
excerpt: posts.excerpt,
publishedAt: posts.publishedAt,
upvotes: posts.upvotesCount,
downvotes: posts.downvotesCount,
externalUrl: posts.externalUrl,
imageUrl: posts.coverImage,
sourceSlug: feed_sources.slug,
sourceName: feed_sources.name,
sourceImage: feed_sources.logoUrl,
})
.from(posts)
.leftJoin(feed_sources, eq(posts.sourceId, feed_sources.id))
.where(
and(
eq(posts.type, "link"),
eq(posts.status, "published"),
eq(feed_sources.status, "active"),
),
)
.orderBy(desc(sql`(${posts.upvotesCount} - ${posts.downvotesCount})`))
.limit(limit);
const [userPosts, feedArticles] = await Promise.all([
userPostsQuery,
feedQuery,
]);
// Transform posts to unified format
const transformedPosts: TrendingItem[] = userPosts.map((p) => ({
type: "post" as const,
id: p.id,
slug: p.slug,
title: p.title,
excerpt: p.excerpt,
publishedAt: p.publishedAt,
readTimeMins: p.readTimeMins ?? 5,
upvotes: p.upvotes ?? 0,
downvotes: p.downvotes ?? 0,
score: (p.upvotes ?? 0) - (p.downvotes ?? 0),
username: p.username ?? undefined,
authorName: p.authorName,
authorImage: p.authorImage,
}));
// Transform feed articles to unified format
const transformedFeed: TrendingItem[] = feedArticles
.filter((f) => f.slug) // Filter out articles without valid slugs
.map((f) => ({
type: "feed" as const,
id: f.id,
slug: f.slug as string,
title: f.title,
excerpt: f.excerpt,
publishedAt: f.publishedAt,
readTimeMins: 5, // Default read time for external articles
upvotes: f.upvotes ?? 0,
downvotes: f.downvotes ?? 0,
score: (f.upvotes ?? 0) - (f.downvotes ?? 0),
sourceSlug: f.sourceSlug ?? undefined,
sourceName: f.sourceName,
sourceImage: f.sourceImage,
externalUrl: f.externalUrl,
imageUrl: f.imageUrl,
}));
// Combine and sort by score, then shuffle for variety
const combined = [...transformedPosts, ...transformedFeed];
combined.sort((a, b) => b.score - a.score);
// Take top items, then shuffle to add variety
const topItems = combined.slice(0, limit * 2);
const shuffled = topItems.sort(() => 0.5 - Math.random());
return shuffled.slice(0, limit);
} catch (error) {
Sentry.captureException(error);
return null;
}
}