Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 51 additions & 34 deletions src/controllers/moment.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import {
bodyToCreateMoment,
bodyToUpdateMoment,
responseFromMyMomentDetail,
responseFromFriendsMoments,
responseFromFriendMomentDetail } from "../dtos/moment.dto.js";
responseFromOtherUserMoments,
responseFromOtherUserMomentDetail } from "../dtos/moment.dto.js";
import {
momentCreate,
momentUpdate,
momentDelete,
getMyMoments,
getMyMomentDetail,
getFriendsMoments,
getFriendMomentDetail } from "../services/moment.service.js";
getOtherUserMoments,
getOtherUserMomentDetail } from "../services/moment.service.js";


export const handleCreateMoment = async (req, res, next) => {
Expand Down Expand Up @@ -228,66 +228,83 @@ export const handleGetMyMomentDetail = async (req, res, next) => {
}
};

export const handleGetOtherUserMoments = async (req, res, next) => {
try {

// userId 확인: 잘못된 값이 전달되는지 확인
const userId = Number(req.params.userId);
console.log("Received userId from params:", req.params.userId); // 확인용 로그 추가
if (isNaN(userId)) {
throw new Error("유효하지 않은 사용자 ID입니다.");
}

export const handleGetFriendsMoments = async (req, res, next) => {
/*
#swagger.tags = ['Moments']
#swagger.summary = '친구의 Moment 목록 조회 API'
#swagger.description = '친구의 페이지에서 해당 친구의 Moment 게시물 목록을 조회합니다.'
#swagger.security = [{
"bearerAuth": []
}]

*/
// getOtherUserMoments 함수에서 userId 확인
const responseData = await getOtherUserMoments(userId);

try {
console.log("친구의 Moment 목록 조회 요청");
const friendId = parseInt(req.params.friendId, 10);
const moments = await getFriendsMoments(friendId);
res.status(StatusCodes.OK).json({
resultType: "SUCCESS",
error: null,
success: {
data: responseFromFriendsMoments(moments)
}
success: { data: responseData }
});

} catch (error) {
console.error("❌ 특정 사용자의 Moment 목록 조회 오류:", error);
next(error);
}
};


export const handleGetFriendMomentDetail = async (req, res, next) => {







export const handleGetOtherUserMomentDetail = async (req, res, next) => {
/*
#swagger.tags = ['Moments']
#swagger.summary = '친구의 특정 Moment 상세 조회 API'
#swagger.description = '친구의 페이지에서 특정 Moment 게시물의 상세 정보를 조회합니다.'
#swagger.security = [{
"bearerAuth": []
}]
#swagger.summary = '특정 사용자의 특정 Moment 상세 조회 API'
#swagger.description = '특정 사용자의 페이지에서 특정 Moment 게시물의 상세 정보를 조회합니다.'
#swagger.security = [{ "bearerAuth": [] }]
#swagger.parameters['userId'] = {
in: "path",
required: true,
description: "조회할 사용자의 ID",
schema: { type: "integer", example: 1234 }
}
#swagger.parameters['momentId'] = {
in: "path",
required: true,
description: "조회할 Moment의 ID",
schema: { type: "integer", example: 456 }
}

*/

try {
console.log("친구의 특정 Moment 상세 조회 요청");
const friendId = parseInt(req.params.friendId, 10);
const momentId = parseInt(req.params.momentId, 10);
const moment = await getFriendMomentDetail(friendId, momentId);
console.log("특정 사용자의 Moment 목록 조회 요청");

const userId = parseInt(req.params.userId, 10);
if (isNaN(userId)) {
throw new Error("유효하지 않은 사용자 ID입니다.");
}

const moments = await getOtherUserMoments(userId);

// 🔍 responseFromOtherUserMoments() 변환 결과 확인
const responseData = responseFromOtherUserMoments(moments);
console.log("Swagger 응답 데이터:", JSON.stringify(responseData, null, 2));

res.status(StatusCodes.OK).json({
resultType: "SUCCESS",
error: null,
success: {
data: responseFromFriendMomentDetail(moment)
data: responseData
}
});
} catch (error) {
console.error("특정 사용자의 Moment 목록 조회 오류:", error);
next(error);
}
};
};

61 changes: 42 additions & 19 deletions src/dtos/moment.dto.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,33 +194,56 @@ export const responseFromMyMomentDetail = (moment) => {
};


// 친구의 Moment 목록 조회 DTO
export const responseFromFriendsMoments = (moments) => {
return moments.map(moment => ({
userId: moment.userId,
momentId: moment.id,
title: moment.title,
status: moment.status,
createdAt: formatDateTime(moment.createdAt),
updatedAt: formatDateTime(moment.updatedAt),
thumbnailUrl: moment.momentContents[0]?.url || null
}));
export const responseFromOtherUserMoments = (moments) => {
if (!Array.isArray(moments)) {
console.error("❌ moments가 배열이 아님:", moments);
return [];
}

return moments.map(moment => {
if (!moment || typeof moment.id === "undefined") {
console.error("❌ moment.id가 유실됨! 원인 추적 필요:", moment);
return null;
}

const transformedMoment = {
userId: Number(moment.userId), // ✅ bigint 변환
momentId: Number(moment.id), // ✅ bigint 변환
title: moment.title,
date: moment.createdAt ? moment.createdAt.toISOString().split("T")[0] : "날짜 없음",
userName: moment.user?.name ?? "알 수 없음",
likingCount: Number(moment.likingCount ?? 0),
commentCount: Number(moment._count?.comments ?? 0),
thumbnailURL: moment.momentContents?.length > 0 ? moment.momentContents[0].url : null
};

return transformedMoment;
}).filter(moment => moment !== null);
};

// 친구의 moment 상세 조회 DTO
export const responseFromFriendMomentDetail = (moment) => {




// 친구의 Moment 상세 조회 DTO
export const responseFromOtherUserMomentDetail = (moment) => {
if (!moment || !moment.id) {
console.error("잘못된 moment 데이터:", moment);
return null;
}

return {
userId: moment.userId,
momentId: moment.id,
title: moment.title,
status: moment.status,
plannerId: moment.plannerId || null,
createdAt: formatDateTime(moment.createdAt),
updatedAt: formatDateTime(moment.updatedAt),
date: formatDate(moment.createdAt),
plannerId: moment.plannerId ?? null,
createdAt: formatDateTime(moment.createdAt),
updatedAt: formatDateTime(moment.updatedAt),
momentContents: moment.momentContents.map(content => ({
sortOrder: content.sortOrder,
content: content.content,
url: content.url,
url: content.url ?? null
}))
};
};
};
8 changes: 4 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,17 @@ import {
handleDeleteMoment,
handleGetMyMoments,
handleGetMyMomentDetail,
handleGetFriendsMoments,
handleGetFriendMomentDetail
handleGetOtherUserMoments,
handleGetOtherUserMomentDetail
} from "./controllers/moment.controller.js";

app.post("/moments", authenticateJWT, handleCreateMoment); //모먼트 생성
app.patch("/moments/:momentId", authenticateJWT, handleUpdateMoment); //모먼트 수정
app.delete("/moments/:momentId", authenticateJWT, handleDeleteMoment); //모먼트 삭제
app.get("/mypage/moments", authenticateJWT, handleGetMyMoments); //마이페이지에서 나의 moment게시글 목록 조회
app.get("/mypage/moments/:momentId", authenticateJWT, handleGetMyMomentDetail); //마이페이지에서 나의 특정 moment게시물 조회
app.get("/friends/:friendId/moments", authenticateJWT, handleGetFriendsMoments) //친구페이지 moment게시물 목록 조회
app.get("/friends/:friendId/moments/momentId", authenticateJWT, handleGetFriendMomentDetail); //친구페이지 특정 moment게시물 조회
app.get("/users/:userId/moments", authenticateJWT, handleGetOtherUserMoments) //친구페이지 moment게시물 목록 조회
app.get("/users/:userId/moments/momentId", authenticateJWT, handleGetOtherUserMomentDetail); //친구페이지 특정 moment게시물 조회



Expand Down
107 changes: 55 additions & 52 deletions src/repositories/moment.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,57 +203,60 @@ export const findMyMomentDetail = async (userId, momentId) => {
};


// 친구들의 Moment 목록 조회 (status: public만 조회)
export const findFriendsMoments = async (userId) => {
// 친구 목록 조회
const friendIds = await prisma.friend.findMany({
where: {
fromUserId: BigInt(userId),
isAccepted: true,
},
select: {
toUserId: true,
},
});

const friendUserIds = friendIds.map(friend => friend.toUserId);

return await prisma.moment.findMany({
where: {
userId: { in: friendUserIds },
status: 'public',
},
include: {
momentContents: true,
},
orderBy: {
createdAt: 'desc',
},
});
export const findOtherUserMoments = async (userId) => {
try {

const moments = await prisma.moment.findMany({
where: { userId: BigInt(userId) },
include: {
user: { select: { name: true } },
momentContents: { select: { url: true }, take: 1 },
_count: { select: { comments: true } }
},
orderBy: { createdAt: "desc" },
});

for (const moment of moments) {
const likesCount = await prisma.like.count({
where: {
entityId: Number(moment.id),
entityType: "moment",
},
});
moment.likingCount = likesCount;
}

return moments;
} catch (error) {
console.error("[findOtherUserMoments] DB 조회 오류:", error);
throw new Error("Moment 목록 조회 실패");
}
};

// 친구의 특정 Moment 상세 조회 (status: public만 조회)
export const findFriendMomentDetail = async (userId, momentId) => {
// 친구인지 확인
const isFriend = await prisma.friend.findFirst({
where: {
fromUserId: BigInt(userId),
isAccepted: true,
},
});

if (!isFriend) {
throw new Error("친구가 아닌 사용자입니다.");
}

return await prisma.moment.findFirst({
where: {
id: BigInt(momentId),
userId: isFriend.toUserId,
status: 'public',
},
include: {
momentContents: true,
},
});
};




// 특정 사용자의 특정 Moment 상세 조회
export const findOtherUserMomentDetail = async (userId, momentId) => {
try {
console.log(`[findOtherUserMomentDetail] API 호출됨! userId: ${userId}, momentId: ${momentId}`);

const moment = await prisma.moment.findUnique({
where: { id: BigInt(momentId) },
include: {
momentContents: true,
planner: true
}
});

if (!moment) {
throw new Error("Moment를 찾을 수 없습니다.");
}

return moment;
} catch (error) {
console.error("[findOtherUserMomentDetail] DB 조회 오류:", error.message);
throw error;
}
};
Loading