|
1 | | -import { count, eq } from "drizzle-orm"; |
| 1 | +import { count, eq , sql} from "drizzle-orm"; |
2 | 2 | import type { FastifyInstance , FastifyRequest} from "fastify"; |
3 | 3 | import { DrizzleClient } from "@/db/index"; |
4 | 4 | import { posts as postsTable } from "@/db/schema/post.schema"; |
| 5 | +import { users as usersTable } from "@/db/schema/user.schema"; |
5 | 6 | import { |
6 | 7 | createPostSchema, |
7 | 8 | postIdParamsSchema, |
@@ -42,16 +43,42 @@ export async function postRoutes(fastify: FastifyInstance) { |
42 | 43 | .send({ success: false, error: "Invalid thread ID" }); |
43 | 44 | const threadId = params.data.id; |
44 | 45 | try { |
45 | | - const [threadPosts, countResult] = await Promise.all([ |
46 | | - DrizzleClient.query.posts.findMany({ |
47 | | - where: (p, { eq }) => eq(p.threadId, threadId), |
48 | | - orderBy: (p, { asc }) => [asc(p.createdAt)], |
49 | | - limit: limit, |
50 | | - offset: offset, |
51 | | - }), |
52 | | - DrizzleClient.select({ total: count() }) |
| 46 | + const postsQuery = DrizzleClient.select({ |
| 47 | + // Post Data |
| 48 | + postId: postsTable.id, |
| 49 | + content: postsTable.content, |
| 50 | + createdAt: postsTable.createdAt, |
| 51 | + // Assuming we will track likes/votes later |
| 52 | + likes: postsTable.vote, |
| 53 | + |
| 54 | + // Author/User Data |
| 55 | + authorId: usersTable.id, |
| 56 | + authorName:sql<string>` |
| 57 | + CASE |
| 58 | + WHEN ${usersTable.username} IS NOT NULL THEN ${usersTable.username} |
| 59 | + ELSE ${usersTable.firstName} |
| 60 | + END |
| 61 | + `.as('authorName'), |
| 62 | + // authorRole: usersTable.role, |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + }) |
| 67 | + .from(postsTable) |
| 68 | + .leftJoin(usersTable, eq(postsTable.createdBy, usersTable.id)) |
| 69 | + .where(eq(postsTable.threadId, threadId)) |
| 70 | + .orderBy(postsTable.createdAt) |
| 71 | + .limit(limit) |
| 72 | + .offset(offset); |
| 73 | + |
| 74 | + // --- 🎯 COUNT QUERY (remains the same) --- |
| 75 | + const countQuery = DrizzleClient.select({ total: count() }) |
53 | 76 | .from(postsTable) |
54 | | - .where(eq(postsTable.threadId, threadId)), |
| 77 | + .where(eq(postsTable.threadId, threadId)); |
| 78 | + |
| 79 | + const [threadPosts, countResult] = await Promise.all([ |
| 80 | + postsQuery, |
| 81 | + countQuery, |
55 | 82 | ]); |
56 | 83 |
|
57 | 84 | return reply.status(200).send({ |
|
0 commit comments