Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

등록&수정 요청 API #39

Merged
merged 23 commits into from
Jul 7, 2024
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
2 changes: 2 additions & 0 deletions src/common/constants/error-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ const ErrorMessage = Object.freeze({
SEARCH_WORDS_ERROR: '검색 결과 조회 중 오류가 발생하였습니다.',
GET_WORDS_ERROR: '단어 조회 중 오류가 발생하였습니다.',
RANK_WORDS_ERROR: '인기 검색어 조회 중 오류가 발생하였습니다.',
RELATED_WORDS_ERROR: '연관 검색어 조회 중 오류가 발생하였습니다.',
REGISTER_WORDS_ERROR: '등록 요청 중 오류가 발생하였습니다.',

// REQUEST
GET_REQUESTS_ERROR: '요청 조회중 오류가 발생하였습니다.',
Expand Down
3 changes: 3 additions & 0 deletions src/common/constants/success-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ const SuccessMessage = Object.freeze({
// WORD - 조회
GET_WORDS_SUCCESS: '단어 조회 성공',
RELATED_WORDS_SUCCESS: '연관 검색어 조회 성공',

// Word - 등록요청
REGISTER_WORDS_SUCCESS: '등록 요청 성공',
});

module.exports = SuccessMessage;
18 changes: 18 additions & 0 deletions src/routes/user/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,24 @@ exports.delRecentSearch = async (req, res) => {
}
};

// 새로운 단어 등록 및 수정
exports.postWords = async (req, res) => {
try {
const { _id } = req.user;
const { nickname } = req.params; // URL 파라미터에서 nickname 추출
const { formData, type } = req.body; // formData와 type을 요청 본문에서 분리

const result = await userService.postWords(_id, formData, nickname, type);

sendResponse.ok(res, {
message: SuccessMessage.REGISTER_WORDS_SUCCESS,
data: result
});
} catch (error) {
console.log("Error during postWords:", error);
sendResponse.fail(req, res, ErrorMessage.REGISTER_WORDS_ERROR);
}
};
exports.UserRequests = async (req, res) => {
try{
const { _id } = req.user;
Expand Down
55 changes: 52 additions & 3 deletions src/routes/user/user.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,57 @@ exports.updateRecentSearch = async (_id, searchTerm) => {
}
};

// 단어 추가 및 수정
exports.postWords = async (userId, formData, nickname, type) => {
try {
const user = await User.findById(userId).exec();
if (!user) {
throw new Error('User not found');
}

console.log("User before modification:", JSON.stringify(user.requests, null, 2));

if (type === 'add') {
user.requests.push({
word: formData.devTerm,
info: formData.addInfo,
awkPron: formData.awkPron,
comPron: formData.commonPron,
deletedAt: null,
status: 'pend',
type: 'add',
suggestedBy: nickname // nickname 추가
});
} else if (type === 'mod') {
const request = user.requests.find(req => req.word === formData.devTerm);
if (!request) {
user.requests.push({
word: formData.devTerm,
info: formData.addInfo,
awkPron: formData.awkPron,
comPron: formData.commonPron,
deletedAt: null,
status: 'pend',
type: 'mod',
suggestedBy: nickname // nickname 추가
})
} else {
console.log('이미 같은 단어 수정 요청이 존재합니다.');
throw new Error('Word not found');
}
} else {
throw new Error('Invalid type');
}

await user.save();
console.log("User after modification:", JSON.stringify(user.requests, null, 2));
return user.requests.find(req => req.word === formData.devTerm);
} catch (err) {
console.error(err);
throw err;
}
};

exports.getUserRequests = async (userId) => {
try {
const user = await User.findById(userId).select('requests').exec();
Expand Down Expand Up @@ -153,7 +204,6 @@ exports.getRole = async (userId) => {

exports.updateRequest = async (requestId, formData) => {
try {
console.log("updateRequest 레포진입!!!!!!!!!!!!", requestId, formData)
const user = await User.findOne({ 'requests._id': requestId }).select('requests').exec();
if (!user) {
throw new Error('User not found');
Expand Down Expand Up @@ -201,5 +251,4 @@ exports.updateRequestState = async (userId, requestId, status) => {

} catch (err) {
console.error(err);
}
};
}}
7 changes: 6 additions & 1 deletion src/routes/user/user.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ const {
logout,
recentSearches,
delRecentSearch,
postWords,
UserRequests,
UserRequestsAll,
deleteRequest,
updateRequest,
getRole,
updateRequestState,
} = require('./user.controller');
const { isLoggedIn, isNotLoggedIn } = require('../../common/utils/auth');
const { isLoggedIn, isNotLoggedIn, isUser } = require('../../common/utils/auth');
const userRouter = express.Router();

// 회원가입
Expand All @@ -37,6 +38,10 @@ userRouter.get('/profile', isLoggedIn, getProfile);
userRouter.get('/recent', isLoggedIn, recentSearches); // 최근 검색어 조회
userRouter.delete('/:searchTerm', isLoggedIn, delRecentSearch); // 최근 검색어 삭제

//등록 요청
userRouter.post('/requests/:nickname/new', isLoggedIn, postWords);

module.exports = userRouter;
// 요청 조회
userRouter.get('/requests', isLoggedIn, UserRequests); // 요청 목록 조회
userRouter.get('/requests/all', isLoggedIn, UserRequestsAll); // 모든 요청 목록 조회
Expand Down
10 changes: 10 additions & 0 deletions src/routes/user/user.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ exports.updateRecentSearch = async (userID, searchTerm) => {
}
};

// 단어 추가 및 수정
exports.postWords = async (userId, formData, nickname, type) => {
try {
const word = await userRepository.postWords(userId, formData, nickname, type);
return word;
} catch (error) {
console.error('Error in userService.postWords:', error.message);
throw new Error('Error processing word: ' + error.message);
}
};
exports.getUserRequests = async (userId) => {
const requests = await userRepository.getUserRequests(userId);
return requests;
Expand Down
8 changes: 4 additions & 4 deletions src/routes/word/word.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const wordService = require('./word.service');
const userService = require('../user/user.service');
const sendResponse = require('../../common/utils/response-handler');
const ErrorMessage = require('../../common/constants/error-message');
const SucesssMessage = require('../../common/constants/success-message');
const SuccessMessage = require('../../common/constants/success-message');
const { validateRequest } = require('../../common/utils/request.validator');
const { searchTermSchema, relatedTermSchema, wordListSchema } = require('./word.schema');
const { request } = require('express');
Expand All @@ -20,7 +20,7 @@ exports.getSearchWords = async (req, res) => {
if (_id) {
await userService.updateRecentSearch(_id, searchTerm);
}
const message = data ? SucesssMessage.SEARCH_WORDS_SUCCESS : SucesssMessage.SEARCH_WORDS_NONE;
const message = data ? SuccessMessage.SEARCH_WORDS_SUCCESS : SuccessMessage.SEARCH_WORDS_NONE;
sendResponse.ok(res, {
message,
data,
Expand All @@ -39,7 +39,7 @@ exports.getRankWords = async (req, res) => {
try {
const data = await wordService.getRankWords();
sendResponse.ok(res, {
message: SucesssMessage.RANK_WORDS_SUCCESS,
message: SuccessMessage.RANK_WORDS_SUCCESS,
data,
});
} catch (error) {
Expand All @@ -54,7 +54,7 @@ exports.getRelatedWords = async (req, res) => {
searchTerm = validateRequest(relatedTermSchema, searchTerm);
const data = await wordService.getRelatedWords(searchTerm, limit);
sendResponse.ok(res, {
message: SucesssMessage.RELATED_WORDS_SUCCESS,
message: SuccessMessage.RELATED_WORDS_SUCCESS,
data,
});
} catch (error) {
Expand Down
4 changes: 2 additions & 2 deletions src/routes/word/word.route.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
const express = require('express');
const wordRouter = express.Router();

const { isUser } = require('../../common/utils/auth');
const { getRankWords, getSearchWords, getRelatedWords, getAllWords } = require('./word.controller');
const { isLoggedIn, isUser } = require('../../common/utils/auth');

// 전체 단어 목록 (쿼리 스트링에 정렬 & 페이지 정보)
wordRouter.get('/', getAllWords);
Expand All @@ -14,4 +13,5 @@ wordRouter.get('/search/related', getRelatedWords);
// 검색어 조회
wordRouter.post('/search/:searchTerm', isUser, getSearchWords);


module.exports = wordRouter;