Skip to content

Commit

Permalink
Merge pull request #40 from Murakano/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
jjikky authored Jul 7, 2024
2 parents e709fe7 + 2ac4354 commit 670f303
Show file tree
Hide file tree
Showing 15 changed files with 529 additions and 13 deletions.
2 changes: 0 additions & 2 deletions README.md

This file was deleted.

7 changes: 7 additions & 0 deletions src/common/constants/error-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,15 @@ const ErrorMessage = Object.freeze({
RECENT_WORDS_ERROR: '최근 검색어 조회중 오류가 발생하였습니다.',
DELETE_RECENT_WORD_ERROR: '최근 검색어 삭제중 오류가 발생하였습니다.',
SEARCH_WORDS_ERROR: '검색 결과 조회 중 오류가 발생하였습니다.',
GET_WORDS_ERROR: '단어 조회 중 오류가 발생하였습니다.',
RANK_WORDS_ERROR: '인기 검색어 조회 중 오류가 발생하였습니다.',
RELATED_WORDS_ERROR: '연관 검색어 조회 중 오류가 발생하였습니다.',
REGISTER_WORDS_ERROR: '등록 요청 중 오류가 발생하였습니다.',

// REQUEST
GET_REQUESTS_ERROR: '요청 조회중 오류가 발생하였습니다.',
DELETE_REQUEST_ERROR: '요청 삭제중 오류가 발생하였습니다.',
UPDATE_REQUEST_STATE_ERROR: '요청 상태 변경중 오류가 발생하였습니다.',
});

module.exports = ErrorMessage;
17 changes: 15 additions & 2 deletions src/common/constants/success-message.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const SucesssMessage = Object.freeze({
const SuccessMessage = Object.freeze({
// USER - 회원가입
REGISTER_SUCCESSS: '회원가입 성공',
AVAILABLE_NICKNAME: '사용 가능한 닉네임입니다.',
Expand All @@ -20,7 +20,20 @@ const SucesssMessage = Object.freeze({
SEARCH_WORDS_SUCCESS: '검색어 조회 성공',
SEARCH_WORDS_NONE: '검색 결과가 없습니다.',
RANK_WORDS_SUCCESS: '인기 검색어 조회 성공',

// REQUEST - 요청
DELETE_REQUEST_SUCCESS: '요청 삭제 성공',
GET_REQUESTS_SUCCESS: '요청 조회 성공',
GET_ROLE_SUCCESS: '사용자 역할 조회 성공',
UPDATE_REQUEST_SUCCESS: '요청 수정 성공',
UPDATE_REQUEST_STATE_SUCCESS: '요청 상태 변경 성공',

// WORD - 조회
GET_WORDS_SUCCESS: '단어 조회 성공',
RELATED_WORDS_SUCCESS: '연관 검색어 조회 성공',

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

module.exports = SucesssMessage;
module.exports = SuccessMessage;
1 change: 1 addition & 0 deletions src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ router.use('/users', userRouter);

router.use('/words', wordRouter);


// EB health check
router.get('/', (_, res) => {
res.status(200).json({ message: 'Success' });
Expand Down
95 changes: 95 additions & 0 deletions src/routes/user/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../../common/config');


const userService = require('./user.service');
const sendResponse = require('../../common/utils/response-handler');
const ErrorMessage = require('../../common/constants/error-message');
Expand Down Expand Up @@ -218,3 +219,97 @@ exports.delRecentSearch = async (req, res) => {
sendResponse.fail(req, res, ErrorMessage.DELETE_RECENT_WORD_ERROR);
}
};

// 새로운 단어 등록 및 수정
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;
const requests = await userService.getUserRequests(_id);
sendResponse.ok(res, {
message: SuccessMessage.GET_REQUESTS_SUCCESS,
data: { requests },
});
} catch (err) {
console.log(err);
sendResponse.fail(req, res, ErrorMessage.GET_REQUESTS_ERROR);
}
};

exports.UserRequestsAll = async (req, res) => {
try{
const requests = await userService.getUserRequestsAll();
sendResponse.ok(res, {
message: SuccessMessage.GET_REQUESTS_SUCCESS,
data: { requests },
});
} catch (err) {
console.log(err);
sendResponse.fail(req, res, ErrorMessage.GET_REQUESTS_ERROR);
}
}

exports.deleteRequest = async (req, res) => {
try{
const { _id } = req.user; // 현재 로그인한 사용자의 고유 식별자
const { word } = req.params;
await userService.deleteRequest(_id, word);
sendResponse.ok(res, {
message: SuccessMessage.DELETE_REQUEST_SUCCESS,
});
} catch (err) {
console.log(err);
sendResponse.fail(req, res, ErrorMessage.DELETE_REQUEST_ERROR);
}
}

exports.getRole = async (req, res) => {
const { _id } = req.user;
const role = await userService.getRole(_id);
sendResponse.ok(res, {
message: SuccessMessage.GET_ROLE_SUCCESS,
data: { role },
});
}

exports.updateRequest = async (req, res) => {
const { requestId } = req.params;
const { formData } = req.body;
await userService.updateRequest(requestId, formData);
sendResponse.ok(res, {
message: SuccessMessage.UPDATE_REQUEST_SUCCESS
});
}

exports.updateRequestState = async (req, res) => {
try {
const { _id} = req.user;
const { requestId } = req.params;
const { status, formData, requestType } = req.body;

await userService.updateRequestState(_id, requestId, status, formData, requestType);
sendResponse.ok(res, {
message: SuccessMessage.UPDATE_REQUEST_STATE_SUCCESS,
});
} catch (err) {
console.log(err);
sendResponse.fail(req, res, ErrorMessage.UPDATE_REQUEST_STATE_ERROR);
}
}

1 change: 1 addition & 0 deletions src/routes/user/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const requestSchema = new mongoose.Schema(
},
],
info: { type: String },
suggestedBy: { type: String, required: true },
type: { type: String, enum: ['add', 'mod'], required: true },
status: { type: String, enum: ['pend', 'rej', 'app'], default: 'pend' },
deletedAt: { type: Date, default: null },
Expand Down
172 changes: 172 additions & 0 deletions src/routes/user/user.repository.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const User = require('./user.model');
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Types;

exports.createUser = async (userData) => {
try {
Expand Down Expand Up @@ -57,11 +59,14 @@ exports.delRecentSearch = async (_id, searchTerm) => {

exports.updateRecentSearch = async (_id, searchTerm) => {
try {
console.log("id", _id)
console.log("searchTerm", searchTerm)
const user = await User.findById(_id).exec();
if (!user) {
console.log('User not found');
}
const recentSearch = user.recentSearches.find((search) => search.searchTerm === searchTerm);
console.log("recentSearch", recentSearch)
if (recentSearch) {
// 검색어가 이미 존재하는 경우
if (recentSearch.deletedAt) {
Expand All @@ -80,3 +85,170 @@ exports.updateRecentSearch = async (_id, searchTerm) => {
console.error(err);
}
};

// 단어 추가 및 수정
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();
if (!user) {
throw new Error('User not found');
}
// requests 배열에서 deletedAt이 null인 항목만 필터링
const activeRequests = user.requests.filter(request => request.deletedAt === null);
return activeRequests;

} catch (err) {
console.error(err);
}
};

exports.getUserRequestsAll = async () => {
try {
const users = await User.find({}, { requests: 1, _id: 0 }); // 모든 유저의 requests 필드만 가져옴
const allRequests = [];

users.forEach(user => {
user.requests.forEach(request => {
if (request.deletedAt === null) {
allRequests.push(request);
}
});
});

return allRequests;
} catch (err) {
console.error(err);
}
}

exports.deleteRequest = async (userId, requestWord) => {
try {
const user = await User.findById(userId).select('requests').exec();
if (!user) {
console.log("사용자를 찾을 수 없음");
throw new Error('User not found');
}

const request = user.requests.find(req => req.word === requestWord && req.deletedAt === null);
if (request) {
console.log("삭제할 요청 찾음:", request);
request.deletedAt = Date.now(); // 요청을 삭제로 표시
await user.save();

console.log("요청 삭제 성공");
} else {
}
} catch (err) {
console.error(err);
}
}

exports.getRole = async (userId) => {
try {
const user = await User.findById(userId).select('role').exec();
return user.role;
} catch (err) {
console.error(err);
}
}

exports.updateRequest = async (requestId, formData) => {
try {
const user = await User.findOne({ 'requests._id': requestId }).select('requests').exec();
if (!user) {
throw new Error('User not found');
}

const request = user.requests.find(req => req._id.toString() === requestId && req.deletedAt === null);
if (request) {
// formData의 각 속성 값으로 request의 해당 속성 값 업데이트
if (formData.addInfo !== undefined) {
request.info = formData.addInfo;
}
if (formData.awkPron !== undefined) {
request.awkPron = formData.awkPron;
}
if (formData.commonPron !== undefined) {
request.comPron = formData.commonPron;
}
if (formData.devTerm !== undefined) {
request.word = formData.devTerm;
}

await user.save();
} else {
console.log('Request not found or already deleted');
}
} catch (err) {
console.error(err);
}
};

exports.updateRequestState = async (userId, requestId, status) => {
try {
console.log("updateRequestState 레포진입!!!!!!!!!!!!", userId, requestId, status)
const user = await User.findOneAndUpdate(
{ 'requests._id': requestId },
{ $set: { 'requests.$.status': status } },
{ new: true }
).exec();

if (!user) {
console.log('Request not found');
} else {
console.log('Request status updated successfully');
}

} catch (err) {
console.error(err);
}}
24 changes: 23 additions & 1 deletion src/routes/user/user.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +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 @@ -31,4 +38,19 @@ 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); // 모든 요청 목록 조회
userRouter.get('/role', isLoggedIn, getRole); // 사용자 역할 가져오기
userRouter.delete('/requests/:word', isLoggedIn, deleteRequest); // 사용자 요청 삭제
userRouter.post('/requests/:requestId', isLoggedIn, updateRequest); // 사용자 요청 수정


//요청 상태 변경
userRouter.post('/requests/:requestId/status', isLoggedIn, updateRequestState); // 사용자 요청 status 변경

module.exports = userRouter;
Loading

0 comments on commit 670f303

Please sign in to comment.