Skip to content

Commit

Permalink
fix: 좋아요 목록 안 불러와지는 문제 수정 및 Post 응답하도록 개선
Browse files Browse the repository at this point in the history
  • Loading branch information
jinyongp committed Nov 10, 2023
1 parent 9a7ac6c commit faec2b1
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 63 deletions.
13 changes: 7 additions & 6 deletions src/controllers/community/posts/:postId([0-9]+)/likes.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
import { createRouter } from "router";
import { likes } from "services";
import { Post, toPost } from "models";

export const likePost = createRouter({
description: "게시글에 좋아요를 합니다.",
method: "POST",
authorized: true,
async handler(ctx): Promise<boolean> {
await likes.likePost({
async handler(ctx): Promise<Post> {
const post = await likes.likePost({
postId: +ctx.param.postId,
userId: ctx.auth.user.id,
});
return true;
return toPost(post);
},
});

export const unlikePost = createRouter({
description: "게시글에 좋아요를 취소합니다.",
method: "DELETE",
authorized: true,
async handler(ctx): Promise<boolean> {
await likes.unlikePost({
async handler(ctx): Promise<Post> {
const post = await likes.unlikePost({
postId: +ctx.param.postId,
userId: ctx.auth.user.id,
});
return true;
return toPost(post);
},
});
4 changes: 1 addition & 3 deletions src/controllers/my/followers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ export const getMyFollowers = createRouter({
authorized: true,
async handler(ctx): Promise<User[]> {
const options = normalizePaginationQuery(ctx.query);
const list = await users.findFollowers(options, {
userId: ctx.auth.user.id,
});
const list = await users.findFollowers(ctx.auth.user.id, options);
return Promise.all(list.map(async (user) => toUser(user)));
},
});
4 changes: 1 addition & 3 deletions src/controllers/my/followings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ export const getMyFollowings = createRouter({
authorized: true,
async handler(ctx): Promise<User[]> {
const options = normalizePaginationQuery(ctx.query);
const list = await users.findFollowings(options, {
userId: ctx.auth.user.id,
});
const list = await users.findFollowings(ctx.auth.user.id, options);
return Promise.all(list.map(async (user) => toUser(user)));
},
});
14 changes: 5 additions & 9 deletions src/controllers/my/liked-posts/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import { createRouter } from "router";
import { likes } from "services";
import { Post, RawCommunityPost, toCommunityPost } from "models";
import { Post, toCommunityPost } from "models";
import { normalizePaginationQuery } from "utils/pagination";

export const getMyLikedPosts = createRouter({
description: "내가 좋아요한 게시글 목록을 불러옵니다.",
authorized: true,
async handler(ctx): Promise<Post[]> {
const options = normalizePaginationQuery(ctx.query);
const list = await likes.findAllPosts(
options,
{
userId: ctx.auth.user.id,
},
{ user: true },
);
const list = await likes.findAllPosts(ctx.auth.user.id, options, {
userId: ctx.auth.user.id,
});
return Promise.all(
list.map(({ post }) => ({
...toCommunityPost(post as unknown as RawCommunityPost),
...toCommunityPost(post),
liked: true,
})),
);
Expand Down
2 changes: 1 addition & 1 deletion src/models/CommunityPost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export interface CommunityPost extends Exclude<Post, "userId"> {
user: User;
}

export interface RawCommunityPost extends Exclude<RawPost, "userId"> {
export interface RawCommunityPost extends RawPost {
user: RawUser;
}

Expand Down
4 changes: 2 additions & 2 deletions src/models/Post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface RawPost {
url: string;
postTags: { tag: string }[];
publishedAt: Date;
postLikes: { userId: number }[];
postLikes?: { userId: number }[];
}

export function toPost(raw: RawPost): Post {
Expand All @@ -33,7 +33,7 @@ export function toPost(raw: RawPost): Post {
content: raw.content,
url: raw.url,
tags: raw.postTags.map(({ tag }) => tag),
liked: raw.postLikes.length > 0,
liked: Boolean(raw.postLikes?.length),
publishedAt: dateToUnixTime(raw.publishedAt),
};
}
37 changes: 29 additions & 8 deletions src/services/likes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { CursorBasedPagination } from "utils/pagination";
import { userInclude } from "./users";

export function findAllPosts(
authUserId: number,
pagination?: CursorBasedPagination,
where?: { userId?: number },
include?: { user?: boolean },
) {
const { cursor, limit, desc } = pagination ?? {};
const { userId } = where ?? {};
Expand All @@ -17,11 +17,9 @@ export function findAllPosts(
post: {
include: {
postTags: true,
...(include?.user && {
user: {
include: userInclude(userId),
},
}),
user: {
include: userInclude(authUserId),
},
},
},
},
Expand All @@ -36,9 +34,20 @@ export function findAllPosts(

export async function likePost(where: { userId: number; postId: number }) {
try {
return await prisma.postLike.create({
const result = await prisma.postLike.create({
data: where,
include: {
post: {
include: {
postTags: true,
postLikes: {
take: 1,
},
},
},
},
});
return result.post;
} catch (error) {
if (error instanceof PrismaClientKnownRequestError) {
// The .code property can be accessed in a type-safe manner
Expand All @@ -55,14 +64,26 @@ export async function likePost(where: { userId: number; postId: number }) {

export async function unlikePost(where: { userId: number; postId: number }) {
try {
return await prisma.postLike.delete({
const result = await prisma.postLike.delete({
where: {
postLikeIndex: {
userId: where.userId,
postId: where.postId,
},
},
include: {
post: {
include: {
postTags: true,
postLikes: {
take: 1,
},
},
},
},
});
result.post.postLikes = [];
return result.post;
} catch (error) {
if (error instanceof PrismaClientKnownRequestError) {
if (error.code === "P2025") {
Expand Down
62 changes: 31 additions & 31 deletions src/services/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,34 @@ import { prisma } from "prisma";
import { HttpError } from "utils/http";
import { CursorBasedPagination } from "utils/pagination";

export const userInclude = (userId?: number) =>
({
_count: {
select: {
posts: true,
followers: true,
followings: true,
blogs: true,
},
},
blogs: {
select: {
lastPublishedAt: true,
},
orderBy: {
lastPublishedAt: "desc",
},
take: 1,
// TODO: AuthUser Context 전달하도록 개선
export const userInclude = (authUserId: number): Prisma.UserInclude => ({
_count: {
select: {
posts: true,
followers: true,
followings: true,
blogs: true,
},
followers: {
where: { followerId: userId },
take: 1,
},
blogs: {
select: {
lastPublishedAt: true,
},
followings: {
where: { followingId: userId },
take: 1,
orderBy: {
lastPublishedAt: "desc",
},
}) satisfies Prisma.UserInclude;
take: 1,
},
followers: {
where: { followerId: authUserId },
take: 1,
},
followings: {
where: { followingId: authUserId },
take: 1,
},
});

export async function findAuthUser(id: number) {
return await prisma.user.findUnique({
Expand Down Expand Up @@ -160,15 +160,15 @@ export function sync(id: number) {
}

export async function findFollowers(
userId: number,
pagination?: CursorBasedPagination,
where?: { userId: number },
) {
const { cursor, limit, desc } = pagination ?? {};
const followerMaps = await prisma.follow.findMany({
where: { followingId: where?.userId },
where: { followingId: userId },
include: {
follower: {
include: userInclude(where?.userId),
include: userInclude(userId),
},
},
...(cursor && {
Expand All @@ -182,15 +182,15 @@ export async function findFollowers(
}

export async function findFollowings(
userId: number,
pagination?: CursorBasedPagination,
where?: { userId: number },
) {
const { cursor, limit, desc } = pagination ?? {};
const followingMaps = await prisma.follow.findMany({
where: { followerId: where?.userId },
where: { followerId: userId },
include: {
following: {
include: userInclude(where?.userId),
include: userInclude(userId),
},
},
...(cursor && {
Expand Down

0 comments on commit faec2b1

Please sign in to comment.