Skip to content
Snippets Groups Projects
Commit 03c8c812 authored by tpgus2603's avatar tpgus2603
Browse files

refactor 스케쥴dto및 엔티티모델 수정/#11

parent a761f6de
No related branches found
No related tags found
2 merge requests!31Develop,!14[#11] dto설정, 프렌드,서비스로직 테스트 및 로직변경
...@@ -3,7 +3,11 @@ ...@@ -3,7 +3,11 @@
const { Op } = require('sequelize'); const { Op } = require('sequelize');
const Friend = require('../models/Friend'); const Friend = require('../models/Friend');
const User = require('../models/User'); const User = require('../models/User');
const sequelize = require('../config/sequelize'); // 트랜잭션을 위해 추가 const sequelize = require('../config/sequelize');
// DTO 임포트
const FriendRequestDTO = require('../dtos/FriendRequestDTO');
const FriendListDTO = require('../dtos/FriendListDTO');
class FriendService { class FriendService {
/** /**
...@@ -24,7 +28,7 @@ class FriendService { ...@@ -24,7 +28,7 @@ class FriendService {
* 친구 요청 보내기 * 친구 요청 보내기
* @param {number} userId - 친구 요청을 보내는 사용자 ID * @param {number} userId - 친구 요청을 보내는 사용자 ID
* @param {number} friendId - 친구 요청을 받는 사용자 ID * @param {number} friendId - 친구 요청을 받는 사용자 ID
* @returns {Promise<Friend>} - 생성된 친구 요청 객체 * @returns {Promise<FriendRequestDTO>} - 생성된 친구 요청 DTO
* @throws {Error} - 유효하지 않은 요청일 경우 * @throws {Error} - 유효하지 않은 요청일 경우
*/ */
async sendFriendRequest(userId, friendId) { async sendFriendRequest(userId, friendId) {
...@@ -35,12 +39,40 @@ class FriendService { ...@@ -35,12 +39,40 @@ class FriendService {
throw new Error('Cannot send friend request to yourself'); throw new Error('Cannot send friend request to yourself');
} }
// 기존 친구 관계 확인 (이미 친구인 경우)
const existingFriend = await Friend.findOne({
where: {
[Op.or]: [
{ requester_id: userId, receiver_id: friendId },
{ requester_id: friendId, receiver_id: userId },
],
status: 'ACCEPTED',
},
});
if (existingFriend) {
throw new Error('Friend request already exists');
}
try { try {
return await Friend.create({ const friendRequest = await Friend.create({
requester_id: userId, requester_id: userId,
receiver_id: friendId, receiver_id: friendId,
status: 'PENDING' status: 'PENDING'
}); });
// DTO로 변환하여 반환
const friendRequestWithDetails = await Friend.findByPk(friendRequest.id, {
include: [
{ model: User, as: 'requester', attributes: ['id', 'name', 'email'] },
{ model: User, as: 'receiver', attributes: ['id', 'name', 'email'] }
]
});
// 디버깅을 위해 로그 추가
//console.log('FriendRequestWithDetails:', friendRequestWithDetails.toJSON());
return new FriendRequestDTO(friendRequestWithDetails.toJSON());
} catch (error) { } catch (error) {
if (error.name === 'SequelizeUniqueConstraintError') { if (error.name === 'SequelizeUniqueConstraintError') {
throw new Error('Friend request already exists'); throw new Error('Friend request already exists');
...@@ -52,46 +84,48 @@ class FriendService { ...@@ -52,46 +84,48 @@ class FriendService {
/** /**
* 받은 친구 요청 목록 조회 * 받은 친구 요청 목록 조회
* @param {number} userId - 요청을 받은 사용자 ID * @param {number} userId - 요청을 받은 사용자 ID
* @returns {Promise<Array>} - 받은 친구 요청 목록 * @returns {Promise<Array<FriendRequestDTO>>} - 받은 친구 요청 목록 DTO 배열
*/ */
async getReceivedRequests(userId) { async getReceivedRequests(userId) {
return Friend.findAll({ const receivedRequests = await Friend.findAll({
where: { where: {
receiver_id: userId, receiver_id: userId,
status: 'PENDING' status: 'PENDING'
}, },
include: [{ include: [
model: User, { model: User, as: 'requester', attributes: ['id', 'name', 'email'] },
as: 'requester', { model: User, as: 'receiver', attributes: ['id', 'name', 'email'] } // 추가
attributes: ['id', 'name', 'email'] ]
}]
}); });
return receivedRequests.map(req => new FriendRequestDTO(req));
} }
/** /**
* 보낸 친구 요청 목록 조회 * 보낸 친구 요청 목록 조회
* @param {number} userId - 요청을 보낸 사용자 ID * @param {number} userId - 요청을 보낸 사용자 ID
* @returns {Promise<Array>} - 보낸 친구 요청 목록 * @returns {Promise<Array<FriendRequestDTO>>} - 보낸 친구 요청 목록 DTO 배열
*/ */
async getSentRequests(userId) { async getSentRequests(userId) {
return Friend.findAll({ const sentRequests = await Friend.findAll({
where: { where: {
requester_id: userId, requester_id: userId,
status: 'PENDING' status: 'PENDING'
}, },
include: [{ include: [
model: User, { model: User, as: 'receiver', attributes: ['id', 'name', 'email'] },
as: 'receiver', { model: User, as: 'requester', attributes: ['id', 'name', 'email'] } // 추가
attributes: ['id', 'name', 'email'] ]
}]
}); });
return sentRequests.map(req => new FriendRequestDTO(req));
} }
/** /**
* 친구 요청 수락 * 친구 요청 수락
* @param {number} userId - 요청을 수락하는 사용자 ID * @param {number} userId - 요청을 수락하는 사용자 ID
* @param {number} friendId - 친구 요청을 보낸 사용자 ID * @param {number} friendId - 친구 요청을 보낸 사용자 ID
* @returns {Promise<Friend>} - 업데이트된 친구 요청 객체 * @returns {Promise<FriendRequestDTO>} - 업데이트된 친구 요청 DTO
* @throws {Error} - 친구 요청이 존재하지 않을 경우 * @throws {Error} - 친구 요청이 존재하지 않을 경우
*/ */
async acceptFriendRequest(userId, friendId) { async acceptFriendRequest(userId, friendId) {
...@@ -113,7 +147,16 @@ class FriendService { ...@@ -113,7 +147,16 @@ class FriendService {
await request.update({ status: 'ACCEPTED' }, { transaction }); await request.update({ status: 'ACCEPTED' }, { transaction });
await transaction.commit(); await transaction.commit();
return request;
// DTO로 변환하여 반환
const updatedRequest = await Friend.findByPk(request.id, {
include: [
{ model: User, as: 'requester', attributes: ['id', 'name', 'email'] },
{ model: User, as: 'receiver', attributes: ['id', 'name', 'email'] }
]
});
return new FriendRequestDTO(updatedRequest);
} catch (error) { } catch (error) {
await transaction.rollback(); await transaction.rollback();
throw error; throw error;
...@@ -146,9 +189,11 @@ class FriendService { ...@@ -146,9 +189,11 @@ class FriendService {
/** /**
* 친구 목록 조회 * 친구 목록 조회
* @param {number} userId - 친구 목록을 조회할 사용자 ID * @param {number} userId - 친구 목록을 조회할 사용자 ID
* @returns {Promise<Array>} - 친구 목록 * @param {number} limit - 한 페이지에 표시할 친구 수
* @param {number} offset - 페이징 오프셋
* @returns {Promise<Array<FriendListDTO>>} - 친구 목록 DTO 배열
*/ */
async getFriendList(userId) { async getFriendList(userId, limit = 20, offset = 0) {
const friends = await Friend.findAll({ const friends = await Friend.findAll({
where: { where: {
[Op.or]: [ [Op.or]: [
...@@ -168,22 +213,16 @@ class FriendService { ...@@ -168,22 +213,16 @@ class FriendService {
as: 'receiver', as: 'receiver',
attributes: ['id', 'name', 'email'] attributes: ['id', 'name', 'email']
} }
] ],
order: [['id', 'ASC']], // 일관된 정렬 순서 추가
limit,
offset
}); });
return friends.map(friend => { // 디버깅을 위해 로그 추가
const isRequester = friend.requester_id === userId; //console.log(`getFriendList: Retrieved ${friends.length} friends with limit=${limit} and offset=${offset}`);
const friendInfo = isRequester ? friend.receiver : friend.requester;
return friends.map(friend => new FriendListDTO(friend, userId));
return {
id: friend.id,
status: friend.status,
createdAt: friend.createdAt,
updatedAt: friend.updatedAt,
friendInfo: friendInfo,
relationshipType: isRequester ? 'sent' : 'received'
};
});
} }
/** /**
......
// test/friendService.test.js
const sequelize = require('../config/sequelize'); // Sequelize 인스턴스 임포트
const User = require('../models/User');
const Friend = require('../models/Friend');
const friendService = require('../services/friendService'); // FriendService 임포트
// Sequelize의 Op를 가져오기 위해 추가
const { Op } = require('sequelize');
beforeAll(async () => {
await sequelize.sync({ force: true });
});
beforeEach(async () => {
await sequelize.sync({ force: true });
// 더미 사용자 생성
await User.bulkCreate([
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
{ id: 3, name: 'Charlie', email: 'charlie@example.com' },
]);
});
afterAll(async () => {
// 모든 테스트가 끝난 후 데이터베이스 연결을 종료합니다.
await sequelize.close();
});
describe('Friend Service', () => {
describe('validUser', () => {
test('should return user when user exists', async () => {
const user = await friendService.validUser(1);
expect(user).toBeDefined();
expect(user.name).toBe('Alice');
});
test('should throw error when user does not exist', async () => {
await expect(friendService.validUser(999)).rejects.toThrow('User not found');
});
});
describe('sendFriendRequest', () => {
test('should send a friend request successfully', async () => {
const friendRequestDTO = await friendService.sendFriendRequest(1, 3); // Alice sends request to Charlie
console.log('sendFriendRequest DTO:', friendRequestDTO); // 디버깅을 위한 로그 추가
expect(friendRequestDTO).toBeDefined();
expect(friendRequestDTO.requester.id).toBe(1);
expect(friendRequestDTO.receiver.id).toBe(3);
expect(friendRequestDTO.status).toBe('PENDING');
});
test('should throw error when sending friend request to self', async () => {
await expect(friendService.sendFriendRequest(1, 1)).rejects.toThrow('Cannot send friend request to yourself');
});
test('should throw error when sending duplicate friend request', async () => {
// Alice sends a friend request to Bob
await friendService.sendFriendRequest(1, 2);
// Bob accepts Alice's request
await friendService.acceptFriendRequest(2, 1);
// Alice tries to send another friend request to Bob
await expect(friendService.sendFriendRequest(1, 2)).rejects.toThrow('Friend request already exists');
});
test('should throw error when user does not exist', async () => {
await expect(friendService.sendFriendRequest(1, 999)).rejects.toThrow('User not found');
await expect(friendService.sendFriendRequest(999, 1)).rejects.toThrow('User not found');
});
});
describe('getReceivedRequests', () => {
test('friend requests', async () => {
await friendService.sendFriendRequest(3, 1);
const receivedRequests = await friendService.getReceivedRequests(1);
expect(receivedRequests.length).toBe(1);
expect(receivedRequests[0].requester.name).toBe('Charlie');
});
test('not send request', async () => {
const receivedRequests = await friendService.getReceivedRequests(2); // Bob has no pending requests
expect(receivedRequests.length).toBe(0);
});
});
describe('getSentRequests', () => {
test('should retrieve sent friend requests', async () => {
await friendService.sendFriendRequest(1, 3);
const sentRequests = await friendService.getSentRequests(1);
expect(sentRequests.length).toBe(1);
expect(sentRequests[0].receiver.name).toBe('Charlie');
});
test('should return empty array when no sent requests', async () => {
const sentRequests = await friendService.getSentRequests(3); // Charlie has not sent any PENDING requests
expect(sentRequests.length).toBe(0);
});
});
describe('acceptFriendRequest', () => {
test('should accept a pending friend request successfully', async () => {
await friendService.sendFriendRequest(3, 1);
const updatedRequestDTO = await friendService.acceptFriendRequest(1, 3);
expect(updatedRequestDTO).toBeDefined();
expect(updatedRequestDTO.status).toBe('ACCEPTED');
// Db상태 확인
const request = await Friend.findOne({
where: {
requester_id: 3,
receiver_id: 1,
},
});
expect(request.status).toBe('ACCEPTED');
});
test('should throw error when accepting non-existing friend request', async () => {
await expect(friendService.acceptFriendRequest(1, 999)).rejects.toThrow('Friend request not found');
});
});
describe('rejectFriendRequest', () => {
test('should reject a pending friend request successfully', async () => {
await friendService.sendFriendRequest(2, 3);
const result = await friendService.rejectFriendRequest(3, 2);
expect(result).toBe(1);
const request = await Friend.findOne({
where: {
requester_id: 2,
receiver_id: 3,
},
});
expect(request).toBeNull();
});
test('should throw error when rejecting non-existing friend request', async () => {
await expect(friendService.rejectFriendRequest(1, 999)).rejects.toThrow('Friend request not found');
});
});
describe('getFriendList', () => {
test('should retrieve friend list with correct pagination', async () => {
await friendService.sendFriendRequest(1, 2);
await friendService.acceptFriendRequest(2, 1);
await friendService.sendFriendRequest(1, 3);
await friendService.acceptFriendRequest(3, 1);
// 추가 더미데이터 생성
for (let i = 4; i <= 23; i++) {
// Create dummy users
await User.create({
id: i,
name: `User${i}`,
email: `user${i}@example.com`,
});
// Alice랑 친구맺기
await friendService.sendFriendRequest(1, i);
await friendService.acceptFriendRequest(i, 1);
}
// Alice 친구: Bob (2), Charlie (3), User4부터 User23까지 (총 22명)
const limit = 5;
const offset = 0;
const friendsPage1 = await friendService.getFriendList(1, limit, offset);
//console.log('getFriendList Page 1:', friendsPage1); // 디버깅을 위한 로그 추가
expect(friendsPage1.length).toBe(limit);
const expectedNamesPage1 = ['Bob', 'Charlie', 'User4', 'User5', 'User6'];
const receivedNamesPage1 = friendsPage1.map(friend => friend.friendInfo.name);
expectedNamesPage1.forEach(name => {
expect(receivedNamesPage1).toContain(name);
});
const friendsPage2 = await friendService.getFriendList(1, limit, limit);
//console.log('getFriendList Page 2:', friendsPage2); // 디버깅을 위한 로그 추가
expect(friendsPage2.length).toBe(limit);
const expectedNamesPage2 = ['User7', 'User8', 'User9', 'User10', 'User11'];
const receivedNamesPage2 = friendsPage2.map(friend => friend.friendInfo.name);
expectedNamesPage2.forEach(name => {
expect(receivedNamesPage2).toContain(name);
});
});
test('should return empty array when user has no friends', async () => {
const friends = await friendService.getFriendList(999); // Non-existing user
expect(friends.length).toBe(0);
});
});
describe('deleteFriend', () => {
test('should delete an existing friend relationship successfully', async () => {
await friendService.sendFriendRequest(1, 2);
await friendService.acceptFriendRequest(2, 1);
const result = await friendService.deleteFriend(1, 2);
expect(result).toBe(1);
const relationship = await Friend.findOne({
where: {
[Op.or]: [
{ requester_id: 1, receiver_id: 2 },
{ requester_id: 2, receiver_id: 1 },
],
status: 'ACCEPTED',
},
});
expect(relationship).toBeNull();
});
test('should throw error when deleting a non-existing friend relationship', async () => {
await expect(friendService.deleteFriend(1, 999)).rejects.toThrow('Friend relationship not found');
});
});
});
// services/scheduleService.js
const { Op } = require('sequelize'); const { Op } = require('sequelize');
const Schedule = require('../models/Schedule'); const Schedule = require('../models/Schedule');
const ScheduleResponseDTO = require('../dtos/ScheduleResponseDTO');
const SchedulesResponseDTO = require('../dtos/SchedulesResponseDTO');
class scheduleService { class scheduleService {
/** /**
* transactin wrapper 함수 * 트랜잭션 래퍼 함수
*/ */
async withTransaction(callback) { async withTransaction(callback) {
const transaction = await Schedule.sequelize.transaction(); const transaction = await Schedule.sequelize.transaction();
...@@ -28,9 +32,7 @@ class scheduleService { ...@@ -28,9 +32,7 @@ class scheduleService {
{ is_fixed: true }, { is_fixed: true },
{ {
is_fixed: false, is_fixed: false,
expiry_date: { expiry_date: { [Op.gt]: new Date() }
[Op.gt]: new Date()
}
} }
] ]
}; };
...@@ -70,7 +72,7 @@ class scheduleService { ...@@ -70,7 +72,7 @@ class scheduleService {
* 사용자 스케줄 생성 * 사용자 스케줄 생성
*/ */
async createSchedule({ userId, title, start_time, end_time, is_fixed }) { async createSchedule({ userId, title, start_time, end_time, is_fixed }) {
return this.withTransaction(async (transaction) => { const schedule = await this.withTransaction(async (transaction) => {
this.validateScheduleTime(start_time, end_time); this.validateScheduleTime(start_time, end_time);
const overlap = await this.checkScheduleOverlap(userId, start_time, end_time); const overlap = await this.checkScheduleOverlap(userId, start_time, end_time);
...@@ -89,13 +91,15 @@ class scheduleService { ...@@ -89,13 +91,15 @@ class scheduleService {
return Schedule.create(scheduleData, { transaction }); return Schedule.create(scheduleData, { transaction });
}); });
return new ScheduleResponseDTO(schedule);
} }
/** /**
* 사용자 스케줄 수정 * 사용자 스케줄 수정
*/ */
async updateSchedule(id, userId, updateData) { async updateSchedule(id, userId, updateData) {
return this.withTransaction(async (transaction) => { const updatedSchedule = await this.withTransaction(async (transaction) => {
const schedule = await Schedule.findOne({ const schedule = await Schedule.findOne({
where: { id, user_id: userId }, where: { id, user_id: userId },
transaction transaction
...@@ -118,15 +122,17 @@ class scheduleService { ...@@ -118,15 +122,17 @@ class scheduleService {
} }
const is_fixed = schedule.is_fixed; const is_fixed = schedule.is_fixed;
const updatedData = { const updatedDataWithExpiry = {
...updateData, ...updateData,
expiry_date: is_fixed ? null : this.getNextMonday(updateData.start_time), expiry_date: is_fixed ? null : this.getNextMonday(updateData.start_time),
updatedAt: new Date() updatedAt: new Date()
}; };
delete updatedData.is_fixed; delete updatedDataWithExpiry.is_fixed;
return schedule.update(updatedData, { transaction }); return schedule.update(updatedDataWithExpiry, { transaction });
}); });
return new ScheduleResponseDTO(updatedSchedule);
} }
/** /**
...@@ -143,7 +149,8 @@ class scheduleService { ...@@ -143,7 +149,8 @@ class scheduleService {
throw new Error('Schedule not found'); throw new Error('Schedule not found');
} }
return true; // 삭제 성공 메시지 반환
return { message: 'Schedule successfully deleted' };
}); });
} }
...@@ -152,10 +159,12 @@ class scheduleService { ...@@ -152,10 +159,12 @@ class scheduleService {
*/ */
async getAllSchedules(userId) { async getAllSchedules(userId) {
try { try {
return Schedule.findAll({ const schedules = await Schedule.findAll({
where: this.getScheduleWhereClause(userId), where: this.getScheduleWhereClause(userId),
order: [['start_time', 'ASC']] order: [['start_time', 'ASC']]
}); });
return new SchedulesResponseDTO(schedules);
} catch (error) { } catch (error) {
throw new Error(`Failed to fetch schedules: ${error.message}`); throw new Error(`Failed to fetch schedules: ${error.message}`);
} }
...@@ -174,24 +183,21 @@ class scheduleService { ...@@ -174,24 +183,21 @@ class scheduleService {
throw new Error('Schedule not found'); throw new Error('Schedule not found');
} }
return schedule; return new ScheduleResponseDTO(schedule);
} catch (error) { } catch (error) {
throw new Error(`Failed to fetch schedule: ${error.message}`); throw new Error(`Failed to fetch schedule: ${error.message}`);
} }
} }
/** /**
* 만료된 유동 스케줄 정리 -> utils에 cron job 추가해서 실행하도록 설정 * 만료된 유동 스케줄 정리
*/ */
async cleanExpiredSchedules() { async cleanExpiredSchedules() {
try { try {
await Schedule.destroy({ await Schedule.destroy({
where: { where: {
is_fixed: false, is_fixed: false,
expiry_date: { expiry_date: { [Op.lte]: new Date() }
[Op.lte]: new Date()
}
} }
}); });
} catch (error) { } catch (error) {
...@@ -199,9 +205,8 @@ class scheduleService { ...@@ -199,9 +205,8 @@ class scheduleService {
} }
} }
/** /**
* 스케줄 중복 검사 -> 기존 스케줄 시간대에 추가 못하도록 * 스케줄 중복 검사
*/ */
async checkScheduleOverlap(userId, start_time, end_time, excludeId = null) { async checkScheduleOverlap(userId, start_time, end_time, excludeId = null) {
try { try {
...@@ -209,14 +214,12 @@ class scheduleService { ...@@ -209,14 +214,12 @@ class scheduleService {
user_id: userId, user_id: userId,
[Op.or]: [ [Op.or]: [
{ {
// 새로운 스케줄이 기존 스케줄 내 존재
[Op.and]: [ [Op.and]: [
{ start_time: { [Op.lte]: start_time } }, { start_time: { [Op.lte]: start_time } },
{ end_time: { [Op.gte]: start_time } } { end_time: { [Op.gte]: start_time } }
] ]
}, },
{ {
// 새로운 스케줄이 기존 스케줄을 포함
[Op.and]: [ [Op.and]: [
{ start_time: { [Op.gte]: start_time } }, { start_time: { [Op.gte]: start_time } },
{ start_time: { [Op.lte]: end_time } } { start_time: { [Op.lte]: end_time } }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment