Skip to content
Snippets Groups Projects
Commit 37797c70 authored by 문경호's avatar 문경호
Browse files

Fix: Fix Routine API

parent de8e7655
No related branches found
No related tags found
No related merge requests found
Pipeline #10923 failed
const express = require('express');
const router = express.Router();
const minutesToSeconds = require('../utils/timeconvert'); const minutesToSeconds = require('../utils/timeconvert');
//운동 영상 구조
const Video = require('../models/video');
//루틴 구조
const Routine = require('../models/routine'); const Routine = require('../models/routine');
// 기록할 DB 구조 const Video = require('../models/video');
const Record = require('../models/records');
const routineController = { const routineController = {
recordRoutine: async (req, res) => { recordRoutine: async (req, res) => {
...@@ -30,33 +23,30 @@ const routineController = { ...@@ -30,33 +23,30 @@ const routineController = {
getRoutine: async (req, res) => { getRoutine: async (req, res) => {
try { try {
const userRoutine = await Routine.find({ const userRoutine = await Routine.find({
user_id: req.user.user_id, user_id: req.user.user_id
}).populate('routine_exercises.video'); }).populate('routine_exercises.video').exec();
if (userRoutine.length === 0) { if (userRoutine.length === 0) {
// 아무런 루틴도 없다면 null 로 채워진 루틴 하나를 return const dummyRoutine = [{
const dummyRoutine = [
{
routine_id: null, routine_id: null,
routine_name: null, routine_name: null,
routine_exercises: [ routine_exercises: [{
{
video: { video: {
video_id: null, video_id: null,
video_time: null, video_time: null,
video_tag: null, video_tag: null,
}, },
}, }],
], }];
},
];
return res.json(dummyRoutine); return res.json(dummyRoutine);
} }
return res.status(200).json(userRoutine); return res.status(200).json(userRoutine);
} catch (error) { } catch (error) {
console.error(error); console.error('Routine Error:', error);
res.status(500).json({ res.status(500).json({
message: 'Failed to get user routine', message: 'Failed to get user routine',
error: error.message, error: error.message
}); });
} }
}, },
...@@ -161,6 +151,32 @@ const routineController = { ...@@ -161,6 +151,32 @@ const routineController = {
}); });
} }
}, },
getRoutineVideos: async (req, res) => {
const routine_name = req.query.routine_name; // GET 요청의 쿼리 파라미터
try {
const routine = await Routine.findOne({
user_id: req.user.user_id,
routine_name,
}).populate('routine_exercises.video');
if (!routine) {
return res.status(404).json({ message: 'Routine not Found' });
}
// video 정보만 추출하여 반환
const videos = routine.routine_exercises
.map(exercise => exercise.video)
.filter(video => video); // null/undefined 필터링
res.status(200).json(videos);
} catch (error) {
console.error(error);
res.status(500).json({
message: 'Failed to get routine videos',
error: error.message,
});
}
},
}; };
module.exports = routineController; module.exports = routineController;
\ No newline at end of file
...@@ -30,5 +30,4 @@ const routineSchema = new mongoose.Schema( ...@@ -30,5 +30,4 @@ const routineSchema = new mongoose.Schema(
); );
const Routine = mongoose.model('Routine', routineSchema); const Routine = mongoose.model('Routine', routineSchema);
module.exports = Routine;
module.exports = { Routine };
async function fetchWithOptions(url, options) { async function fetchWithOptions(url, options) {
try { try {
const response = await fetch(url, options); const response = await fetch(url, {
...options,
headers: {
"Authorization": `Bearer ${localStorage.getItem('accessToken')}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP 오류! 상태 코드: ${response.status}`); const errorData = await response.json();
throw new Error(errorData.message || `HTTP 오류! 상태 코드: ${response.status}`);
} }
return await response.json(); return await response.json();
} catch (error) { } catch (error) {
console.error("API 요청 중 에러 발생:", error.message); console.error("API 요청 중 에러 발생:", error.message);
...@@ -11,44 +21,62 @@ async function fetchWithOptions(url, options) { ...@@ -11,44 +21,62 @@ async function fetchWithOptions(url, options) {
} }
} }
async function addExerciseRecord(record) { // 개별 함수들을 export
return await fetchWithOptions('/routine/records', { export const addExerciseRecord = async (record) => {
return await fetchWithOptions('/api/routine/records', {
method: 'POST', method: 'POST',
headers: {
"Authorization": `Bearer ${localStorage.getItem('accessToken')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(record), body: JSON.stringify(record),
}); });
} };
async function getUserRoutines() { export const getUserRoutines = async () => {
return await fetchWithOptions('/routine', { try {
const response = await fetchWithOptions('/api/routine', {
method: 'GET', method: 'GET',
headers: {
"Authorization": `Bearer ${localStorage.getItem('accessToken')}`,
'Content-Type': 'application/json',
},
}); });
// 빈 루틴도 표시할 수 있도록 변환
return response.map(routine => ({
_id: routine._id,
user_id: routine.user_id,
routine_name: routine.routine_name,
routine_exercises: routine.routine_exercises || [], // 빈 배열 처리
created_at: routine.routine_created_at
}));
} catch (error) {
console.error("루틴 데이터 가져오기 실패:", error);
throw error;
} }
};
async function getRoutineVideos(routineName) { export const getRoutineVideos = async (routineName) => {
return await fetchWithOptions(`/routine/videos?routine_name=${routineName}`, { try {
const response = await fetchWithOptions(`/api/routine/videos?routine_name=${encodeURIComponent(routineName)}`, {
method: 'GET', method: 'GET',
headers: {
"Authorization": `Bearer ${localStorage.getItem('accessToken')}`,
'Content-Type': 'application/json',
},
}); });
return response.map(video => ({
title: video.video_title || '',
duration: video.video_time || 0,
link: video.video_url || '',
thumbnail: video.video_thumbnail || ''
}));
} catch (error) {
console.error("루틴 비디오 가져오기 실패:", error);
return []; // 비디오가 없을 경우 빈 배열 반환
} }
};
async function deleteRoutine(routineName) { export const createRoutine = async (routineName) => {
return await fetchWithOptions('/routine', { return await fetchWithOptions('/api/routine', {
method: 'POST',
body: JSON.stringify({ routine_name: routineName }),
});
};
export const deleteRoutine = async (routineName) => {
return await fetchWithOptions('/api/routine', {
method: 'DELETE', method: 'DELETE',
headers: {
"Authorization": `Bearer ${localStorage.getItem('accessToken')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ routine_name: routineName }), body: JSON.stringify({ routine_name: routineName }),
}); });
} }
......
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment