Skip to content

Commit

Permalink
fix: 중복 값 삭제 하는 로직 + isDeleted 안보이게
Browse files Browse the repository at this point in the history
  • Loading branch information
Hyun-git committed Jul 7, 2024
1 parent 55f1d21 commit a1d291a
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 66 deletions.
1 change: 1 addition & 0 deletions src/model/memeRecommendWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const MemeRecommendWatchSchema: Schema = new Schema(
{
deviceId: { type: String, required: true },
startDate: { type: Date, required: true },
isDeleted: { type: Boolean, required: true, default: false },
memeIds: [{ type: Types.ObjectId, ref: 'Meme', required: true }],
},
{
Expand Down
9 changes: 0 additions & 9 deletions src/routes/keyword.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,6 @@ router.post('/', validateCategory, validateKeywordDulication, createKeyword);
* searchCount:
* type: integer
* example: 0
* isDeleted:
* type: boolean
* example: false
* createdAt:
* type: string
* example: "2024-07-05T15:21:34.012Z"
Expand Down Expand Up @@ -271,9 +268,6 @@ router.delete('/:keywordId', getKeywordInfoById, deleteKeyword);
* topReactionImage:
* type: string
* example: "https://example.com/top-reaction-image.jpg"
* isDeleted:
* type: boolean
* example: false
* createdAt:
* type: string
* example: "2024-07-05T15:21:34.012Z"
Expand Down Expand Up @@ -372,9 +366,6 @@ router.get('/top', getTopKeywords);
* searchCount:
* type: integer
* example: 1
* isDeleted:
* type: boolean
* example: false
* createdAt:
* type: string
* example: "2024-07-05T15:21:34.012Z"
Expand Down
41 changes: 14 additions & 27 deletions src/routes/meme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,6 @@ const router = express.Router();
* image:
* type: string
* example: "https://example.com/meme.jpg"
* isDeleted:
* type: boolean
* example: false
* isTodayMeme:
* type: boolean
* example: false
Expand Down Expand Up @@ -167,17 +164,13 @@ router.get('/list', getAllMemeList); // meme 목록 전체 조회 (페이지네
* tags: [Meme]
* summary: 추천 밈 정보 조회
* description: 추천 밈 목록을 조회한다. (현재는 주 단위, 추후 일 단위로 변경될 수 있음)
* requestBody:
* required: false
* content:
* application/json:
* schema:
* type: object
* properties:
* size:
* type: number
* example: 5
* description: 추천 밈 개수 / 기본값 5, body를 넘기지않으면 자동으로 서버에서 5로 설정 후 5개 조회
* parameters:
* - in: query
* name: size
* schema:
* type: number
* example: 5
* description: 추천 밈 개수 / 기본값 5, body를 넘기지않으면 자동으로 서버에서 5로 설정 후 5개 조회
* responses:
* 200:
* description: 추천 밈 목록 조회 성공
Expand Down Expand Up @@ -218,9 +211,6 @@ router.get('/list', getAllMemeList); // meme 목록 전체 조회 (페이지네
* isTodayMeme:
* type: boolean
* example: true
* isDeleted:
* type: boolean
* example: false
* createdAt:
* type: string
* format: date-time
Expand Down Expand Up @@ -357,10 +347,6 @@ router.get('/recommend-memes', getTodayMemeList); // 오늘의 추천 밈 (5개)
* type: boolean
* example: false
* description: 추천 밈 여부
* isDeleted:
* type: boolean
* example: false
* description: 밈 삭제 여부
* createdAt:
* type: string
* format: date-time
Expand Down Expand Up @@ -458,15 +444,15 @@ router.post('/', createMeme); // meme 생성
* reaction:
* type: integer
* example: 0
* watch:
* type: integer
* example: 0
* source:
* type: string
* example: "무한도전 102화"
* isTodayMeme:
* type: boolean
* example: false
* isDeleted:
* type: boolean
* example: false
* createdAt:
* type: string
* format: date-time
Expand Down Expand Up @@ -810,6 +796,7 @@ router.delete('/:memeId', getRequestedMemeInfo, deleteMeme); // meme 삭제
* required: true
* type: string
* - in: path
* required: true
* name: memeId
* schema:
* type: string
Expand Down Expand Up @@ -1007,11 +994,13 @@ router.post('/:memeId/share', getRequestedUserInfo, getRequestedMemeInfo, create
* type: string
* - in: path
* name: memeId
* required: true
* schema:
* type: string
* description: 밈 id
* - in: path
* name: type
* required: true
* schema:
* type: string
* enum: [search, recommend]
Expand Down Expand Up @@ -1120,6 +1109,7 @@ router.post('/:memeId/watch/:type', getRequestedUserInfo, getRequestedMemeInfo,
* type: string
* required: true
* description: 리액션할 밈 id
* responses:
* 201:
* description: Created Meme Reaction
* content:
Expand Down Expand Up @@ -1272,9 +1262,6 @@ router.post('/:memeId/reaction', getRequestedUserInfo, getRequestedMemeInfo, cre
* image:
* type: string
* example: "https://example.com/meme.jpg"
* isDeleted:
* type: boolean
* example: false
* isTodayMeme:
* type: boolean
* example: false
Expand Down
6 changes: 0 additions & 6 deletions src/routes/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,9 +280,6 @@ router.get('/', getRequestedUserInfo, UserController.getUser); // user 조회
* image:
* type: string
* example: "https://example.com/meme.jpg"
* isDeleted:
* type: boolean
* example: false
* isTodayMeme:
* type: boolean
* example: false
Expand Down Expand Up @@ -391,9 +388,6 @@ router.get('/saved-memes', getRequestedUserInfo, UserController.getSavedMemes);
* image:
* type: string
* example: "https://example.com/meme.jpg"
* isDeleted:
* type: boolean
* example: false
* isTodayMeme:
* type: boolean
* example: false
Expand Down
7 changes: 5 additions & 2 deletions src/service/keyword.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ async function deleteKeyword(keywordId: Types.ObjectId): Promise<boolean> {

async function getTopKeywords(limit: number = 6): Promise<IKeywordDocument[]> {
try {
const topKeywords = await KeywordModel.find().sort({ searchCount: -1 }).limit(limit).lean();
const topKeywords = await KeywordModel.find({}, { isDeleted: 0 })
.sort({ searchCount: -1 })
.limit(limit)
.lean();
return topKeywords;
} catch (err) {
logger.error(`Failed to get top keywords: ${err.message}`);
Expand All @@ -65,7 +68,7 @@ async function increaseSearchCount(keywordId: Types.ObjectId): Promise<IKeywordD
const updatedKeyword = await KeywordModel.findOneAndUpdate(
{ _id: keywordId },
{ $inc: { searchCount: 1 } },
{ new: true },
{ new: true, projection: { isDeleted: 0 } },
);
if (!updatedKeyword) {
throw new CustomError(`KeywordId ${keywordId} not found`, HttpCode.NOT_FOUND);
Expand Down
16 changes: 10 additions & 6 deletions src/service/meme.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async function getMemeWithKeywords(memeId: string): Promise<IMemeWithKeywords |
keywords: '$keywords.name',
},
},
{ $project: { keywordIds: 0 } },
{ $project: { keywordIds: 0, isDeleted: 0 } },
]);

if (!meme) {
Expand Down Expand Up @@ -76,7 +76,7 @@ async function getTodayMemeList(limit: number = 5): Promise<IMemeWithKeywords[]>
keywords: '$keywords.name',
},
},
{ $project: { keywordIds: 0 } },
{ $project: { keywordIds: 0, isDeleted: 0 } },
]);

const memeIds = todayMemeList.map((meme) => meme._id);
Expand All @@ -92,7 +92,7 @@ async function getAllMemeList(
): Promise<{ total: number; page: number; totalPages: number; data: IMemeDocument[] }> {
const totalMemes = await MemeModel.countDocuments();

const memeList = await MemeModel.find({ isDeleted: false })
const memeList = await MemeModel.find({ isDeleted: false }, { isDeleted: 0 })
.skip((page - 1) * size)
.limit(size)
.sort({ createdAt: -1 });
Expand Down Expand Up @@ -135,7 +135,7 @@ async function updateMeme(memeId: Types.ObjectId, updateInfo: any): Promise<IMem

async function deleteMeme(memeId: Types.ObjectId): Promise<boolean> {
const deletedMeme = await MemeModel.findOneAndDelete(
{ _id: memeId },
{ _id: memeId, isDeleted: false },
{ $set: { isDeleted: true } },
).lean();

Expand Down Expand Up @@ -165,7 +165,10 @@ async function searchMemeByKeyword(
isDeleted: false,
});

const memeList = await MemeModel.find({ keywordIds: { $in: keyword._id } })
const memeList = await MemeModel.find(
{ isDeleted: false, keywordIds: { $in: keyword._id } },
{ isDeleted: 0 },
)
.skip((page - 1) * size)
.limit(size)
.sort({ reaction: -1 })
Expand Down Expand Up @@ -221,7 +224,7 @@ async function createMemeInteraction(
// 'reaction'인 경우에만 Meme의 reaction 수를 업데이트한다.
if (interactionType === InteractionType.REACTION) {
await MemeModel.findOneAndUpdate(
{ memeId: meme._id },
{ memeId: meme._id, isDeleted: false },
{ $inc: { reaction: 1 } },
{
projection: { _id: 0, createdAt: 0, updatedAt: 0 },
Expand Down Expand Up @@ -270,6 +273,7 @@ async function deleteMemeSave(user: IUserDocument, meme: IMemeDocument): Promise
async function getTopReactionImage(keyword: IKeywordDocument): Promise<string> {
try {
const topReactionMeme: IMemeDocument = await MemeModel.findOne({
isDeleted: false,
keywordIds: { $in: [keyword._id] },
}).sort({
reaction: -1,
Expand Down
47 changes: 31 additions & 16 deletions src/service/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,24 +87,26 @@ async function createUser(deviceId: string): Promise<IUserInfos> {

async function updateLastSeenMeme(user: IUserDocument, meme: IMemeDocument): Promise<IUser> {
try {
const newLastSeenMeme = [...user.lastSeenMeme];
const newLastSeenMeme = [...user.lastSeenMeme].map((id) => id.toString());

const index = newLastSeenMeme.indexOf(meme._id);
const index = newLastSeenMeme.indexOf(meme._id.toString());
// 새 값이 존재하면 해당 값을 배열에서 제거합니다.
if (index !== -1) {
newLastSeenMeme.splice(index, 1);
}
// 새 값을 배열의 첫 번째 위치에 추가합니다.
newLastSeenMeme.unshift(meme._id);
newLastSeenMeme.unshift(meme._id.toString());

if (newLastSeenMeme.length > 10) {
newLastSeenMeme.pop();
}

const newLastSeenMemeList = newLastSeenMeme.map((id) => new Types.ObjectId(id));

const updatedUser = await UserModel.findOneAndUpdate(
{ deviceId: user.deviceId },
{
$set: { lastSeenMeme: newLastSeenMeme },
$set: { lastSeenMeme: newLastSeenMemeList },
},
{
projection: { _id: 0, createdAt: 0, updatedAt: 0 },
Expand All @@ -127,10 +129,13 @@ async function updateLastSeenMeme(user: IUserDocument, meme: IMemeDocument): Pro
async function getLastSeenMemes(user: IUserDocument): Promise<IMemeDocument[]> {
try {
const lastSeenMeme = user.lastSeenMeme;
const memeList = await MemeModel.find({
_id: { $in: lastSeenMeme },
isDeleted: false,
}).lean();
const memeList = await MemeModel.find(
{
_id: { $in: lastSeenMeme },
isDeleted: false,
},
{ isDeleted: 0 },
).lean();

return memeList;
} catch (err) {
Expand All @@ -154,18 +159,24 @@ async function getSavedMemes(
isDeleted: false,
});

const savedMemes = await MemeInteractionModel.find({
deviceId: user.deviceId,
interactionType: InteractionType.SAVE,
isDeleted: false,
})
const savedMemes = await MemeInteractionModel.find(
{
deviceId: user.deviceId,
interactionType: InteractionType.SAVE,
isDeleted: false,
},
{ isDeleted: 0 },
)
.skip((page - 1) * size)
.limit(size)
.sort({ createdAt: -1 })
.lean();

const memeIds = savedMemes.map(({ memeId }) => new Types.ObjectId(memeId));
const memeList = await MemeModel.find({ _id: { $in: memeIds }, isDeleted: false }).lean();
const memeList = await MemeModel.find(
{ _id: { $in: memeIds }, isDeleted: false },
{ isDeleted: 0 },
).lean();

return {
total: totalSavedMemes,
Expand All @@ -182,7 +193,7 @@ async function createMemeRecommendWatch(user: IUserDocument, meme: IMemeDocument
try {
const todayWeekStart = startOfWeek(new Date(), { weekStartsOn: 1 });
const memeRecommendWatch = await MemeRecommendWatchModel.findOne({
memeId: meme._id,
memeIds: meme._id,
startDate: todayWeekStart,
deviceId: user.deviceId,
isDeleted: false,
Expand All @@ -191,8 +202,12 @@ async function createMemeRecommendWatch(user: IUserDocument, meme: IMemeDocument
if (!_.isNull(memeRecommendWatch)) {
logger.info(`Already watched recommend meme - deviceId(${user.deviceId})`);

const updatedMemeList = Array.from(
new Set([...memeRecommendWatch.memeIds, meme._id].map((id) => id.toString())),
).map((id) => new Types.ObjectId(id));

const updatePayload: IMemeRecommendWatchUpdatePayload = {
memeIds: [...memeRecommendWatch.memeIds, meme._id],
memeIds: updatedMemeList,
};

await MemeRecommendWatchModel.findOneAndUpdate(
Expand Down

0 comments on commit a1d291a

Please sign in to comment.