Skip to content

Commit

Permalink
fetch-post-creator
Browse files Browse the repository at this point in the history
  • Loading branch information
benawad committed Aug 14, 2020
1 parent c5468d3 commit 38456e1
Showing 2 changed files with 39 additions and 9 deletions.
1 change: 1 addition & 0 deletions server/src/entities/Post.ts
Original file line number Diff line number Diff line change
@@ -33,6 +33,7 @@ export class Post extends BaseEntity {
@Column()
creatorId: number;

@Field()
@ManyToOne(() => User, (user) => user.posts)
creator: User;

47 changes: 38 additions & 9 deletions server/src/resolvers/post.ts
Original file line number Diff line number Diff line change
@@ -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),

0 comments on commit 38456e1

Please sign in to comment.