@@ -11,6 +11,7 @@ interface Post {
11
11
content : string ;
12
12
timestamp : string ;
13
13
author : string ;
14
+ commentCount ?: number ;
14
15
}
15
16
16
17
export async function createPost ( input : PostInput ) : Promise < Post > {
@@ -37,21 +38,39 @@ export async function createPost(input: PostInput): Promise<Post> {
37
38
}
38
39
39
40
export async function getPosts ( limit = 20 ) : Promise < Post [ ] > {
40
- console . log ( "Fetching posts, limit:" , limit ) ;
41
- const iterator = kv . list < Post > ( { prefix : [ "posts" ] } , { limit } ) ;
41
+ console . log ( "Fetching posts" ) ;
42
+
43
+ // Get all posts
44
+ const postsResults : Post [ ] = [ ] ;
45
+ const iterator = kv . list < Post > ( { prefix : [ "posts" ] } ) ;
42
46
43
- // Collect all entries from the iterator
44
- const results : Post [ ] = [ ] ;
45
47
for await ( const entry of iterator ) {
46
- results . push ( entry . value ) ;
48
+ postsResults . push ( entry . value ) ;
49
+ }
50
+
51
+ // Get comment counts for each post
52
+ const commentCounts = new Map < string , number > ( ) ;
53
+ const commentsIterator = kv . list < Comment > ( { prefix : [ "comments" ] } ) ;
54
+
55
+ for await ( const entry of commentsIterator ) {
56
+ const postId = entry . value . postId ;
57
+ commentCounts . set ( postId , ( commentCounts . get ( postId ) || 0 ) + 1 ) ;
47
58
}
48
59
60
+ // Add comment counts to posts
61
+ const postsWithComments = postsResults . map ( ( post ) => ( {
62
+ ...post ,
63
+ commentCount : commentCounts . get ( post . id ) || 0 ,
64
+ } ) ) ;
65
+
49
66
// Sort posts by timestamp (newest first)
50
- const posts = results . sort ( ( a , b ) =>
51
- new Date ( b . timestamp ) . getTime ( ) - new Date ( a . timestamp ) . getTime ( )
52
- ) ;
67
+ const posts = postsWithComments
68
+ . sort ( ( a , b ) =>
69
+ new Date ( b . timestamp ) . getTime ( ) - new Date ( a . timestamp ) . getTime ( )
70
+ )
71
+ . slice ( 0 , limit ) ;
53
72
54
- console . log ( `Retrieved ${ posts . length } posts from database ` ) ;
73
+ console . log ( `Retrieved ${ posts . length } posts` ) ;
55
74
return posts ;
56
75
}
57
76
@@ -159,7 +178,7 @@ export async function getCommentsByPostId(postId: string): Promise<Comment[]> {
159
178
160
179
// Sort comments by timestamp (newest first)
161
180
const comments = results . sort ( ( a , b ) =>
162
- new Date ( a . timestamp ) . getTime ( ) - new Date ( b . timestamp ) . getTime ( )
181
+ new Date ( b . timestamp ) . getTime ( ) - new Date ( a . timestamp ) . getTime ( )
163
182
) ;
164
183
165
184
console . log ( `Retrieved ${ comments . length } comments for post ${ postId } ` ) ;
0 commit comments