From 38456e12f3a1eadbe5dac4152f78aa3d8c3a8c79 Mon Sep 17 00:00:00 2001 From: Ben Awad Date: Fri, 14 Aug 2020 14:37:58 -0500 Subject: [PATCH] fetch-post-creator --- server/src/entities/Post.ts | 1 + server/src/resolvers/post.ts | 47 +++++++++++++++++++++++++++++------- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/server/src/entities/Post.ts b/server/src/entities/Post.ts index cd4a99db..793b2e48 100644 --- a/server/src/entities/Post.ts +++ b/server/src/entities/Post.ts @@ -33,6 +33,7 @@ export class Post extends BaseEntity { @Column() creatorId: number; + @Field() @ManyToOne(() => User, (user) => user.posts) creator: User; diff --git a/server/src/resolvers/post.ts b/server/src/resolvers/post.ts index 806ef726..8ead40e0 100644 --- a/server/src/resolvers/post.ts +++ b/server/src/resolvers/post.ts @@ -11,6 +11,7 @@ import { FieldResolver, Root, ObjectType, + Info, } from "type-graphql"; import { Post } from "../entities/Post"; import { MyContext } from "../types"; @@ -48,19 +49,47 @@ export class PostResolver { // 20 -> 21 const realLimit = Math.min(50, limit); const reaLimitPlusOne = realLimit + 1; - const qb = getConnection() - .getRepository(Post) - .createQueryBuilder("p") - .orderBy('"createdAt"', "DESC") - .take(reaLimitPlusOne); + + const replacements: any[] = [reaLimitPlusOne]; if (cursor) { - qb.where('"createdAt" < :cursor', { - cursor: new Date(parseInt(cursor)), - }); + replacements.push(new Date(parseInt(cursor))); } - const posts = await qb.getMany(); + const posts = await getConnection().query( + ` + select p.*, + json_build_object( + 'id', u.id, + 'username', u.username, + 'email', u.email, + 'createdAt', u."createdAt", + 'updatedAt', u."updatedAt" + ) creator + from post p + inner join public.user u on u.id = p."creatorId" + ${cursor ? `where p."createdAt" < $2` : ""} + order by p."createdAt" DESC + limit $1 + `, + replacements + ); + + // const qb = getConnection() + // .getRepository(Post) + // .createQueryBuilder("p") + // .innerJoinAndSelect("p.creator", "u", 'u.id = p."creatorId"') + // .orderBy('p."createdAt"', "DESC") + // .take(reaLimitPlusOne); + + // if (cursor) { + // qb.where('p."createdAt" < :cursor', { + // cursor: new Date(parseInt(cursor)), + // }); + // } + + // const posts = await qb.getMany(); + console.log("posts: ", posts); return { posts: posts.slice(0, realLimit),