Skip to content

Commit

Permalink
Merge pull request #26 from 9oormthonUniv-seoultech/develop
Browse files Browse the repository at this point in the history
사진조회, 앨범조회 api 반영
  • Loading branch information
sunyou10 authored Nov 6, 2024
2 parents 4f83152 + b232902 commit a354284
Show file tree
Hide file tree
Showing 6 changed files with 205 additions and 2 deletions.
84 changes: 84 additions & 0 deletions controllers/albumController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
const Photo = require('../models/photo');
const Photobooth = require('../models/photobooth');
const { Sequelize, Op, fn, col } = require('sequelize');

const getAlbum = async (req, res) => {
try {
const user_id = req.params.user_id;
const date = req.query.date ? new Date(req.query.date) : null;
const brand = req.query.brand ? req.query.brand : null;
const location = req.query.location ? req.query.location : null;

let photos;

if (date) { // 날짜 필터링
console.log("date로 들어옴");
const year = date.getFullYear();
const month = date.getMonth() + 1;

photos = await Photo.findAll({
where: {
user_id: user_id,
[Op.and]: [
Sequelize.where(fn('YEAR', col('date')), year),
Sequelize.where(fn('MONTH', col('date')), month)
],
},
order: [['date', 'DESC']],
attributes: ['image_url', 'photo_like'],
});
} else if (brand) { // 브랜드 이름 필터링
console.log("brand로 들어옴");
photos = await Photo.findAll({
where: { user_id: user_id },
include: [
{
model: Photobooth,
where: { brand: brand },
attributes: [],
},
],
order: [['date', 'DESC']],
attributes: ['image_url', 'photo_like'],
});
} else if (location && req.nearbyBoothIds && req.nearbyBoothIds.length > 0) {
// location 필터링 - 미들웨어 반환값 이용, 현재위치 시에는 location=true로 받아야함
console.log("location으로 들어옴");
photos = await Photo.findAll({
where: {
user_id: user_id,
photobooth_id: { [Op.in]: req.nearbyBoothIds },
},
order: [['date', 'DESC']],
attributes: ['image_url', 'photo_like'],
});
} else {
console.log("마지막 else로");
// 필터링 없이 전체 조회 (날짜페이지에서 아무 선택 안했을 때)
photos = await Photo.findAll({
where: { user_id: user_id },
order: [['date', 'DESC']],
attributes: ['image_url', 'photo_like'],
});
}

// 데이터가 없는 경우
if (photos.length === 0) {
return res.status(200).json({
photonum: 0,
});
}

const response = photos.map((photo) => ({
images: photo.image_url,
photo_like: photo.photo_like,
}));

return res.status(200).json(response);
} catch (error) {
console.error("getPhoto error", error);
return res.status(500).json({ error: "Internal Server Error" });
}
};

module.exports = {getAlbum}
48 changes: 47 additions & 1 deletion controllers/photoController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const Photo = require('../models/photo');
const PhotoTemp = require('../models/photoTemp');
const User = require('../models/user');
const Photobooth = require('../models/photobooth');
const { deleteTemp } = require('../middlewares/uploadPhoto');
const { deleteImages } = require('../middlewares/s3');

Expand Down Expand Up @@ -98,5 +99,50 @@ const deletePhoto = async (req, res) => {
}
};

const getPhoto = async (req, res) => {
try {
const {photo_id} = req.params;

const photo = await Photo.findOne({
where: {
id: photo_id,
},
include: [
{
model: Photobooth,
attributes: ['name'],
},
],
attributes: [
'date',
'image_url',
'record',
'hashtag_1',
'hashtag_2',
'hashtag_3',
'photo_like',
],
});

// 사진이 없는 경우
if (!photo) {
return res.status(404).json({ message: '사진을 찾을 수 없습니다.' });
}

const response = {
date: photo.date,
photobooth_name: photo.Photobooth ? photo.Photobooth.name : null,
hashtags: [photo.hashtag_1, photo.hashtag_2, photo.hashtag_3].filter(Boolean), // 빈 해시태그는 제외
image_url: photo.image_url,
record: photo.record,
photo_like : photo.photo_like,
};

return res.status(200).json(response);
} catch (error) {
console.error('Error photo details', error);
return res.status(500).json({ error: 'Internal Server Error' });
}
};

module.exports = { createTemp, updateInfo, updateRecord, savePhoto, deletePhoto };
module.exports = { createTemp, updateInfo, updateRecord, savePhoto, deletePhoto, getPhoto };
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ app.use('/api/photo', photoRouter);
const boothLikeRouter = require('./routes/boothLikeRouter');
app.use('/api/booth', boothLikeRouter);

const albumRouter = require('./routes/albumRouter');
app.use('/api/album', albumRouter);

// 스웨거 세팅
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
Expand Down
58 changes: 58 additions & 0 deletions middlewares/location.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const { Sequelize, Op } = require('sequelize');
const axios = require('axios');
const Photobooth = require('../models/photobooth');

// 미들웨어로 근처 포토부스 위치를 반환
const getNearbyBooths = async (req, res, next) => {
const { latitude = '37.6329741', longitude = '127.0798802', query } = req.query; // 기본 위치는 학교 위치로 설정
const radius = 1000; // 반경 1km

try {
let searchLatitude = parseFloat(latitude);
let searchLongitude = parseFloat(longitude);

if (query) {
console.log('Search Query:', query);
// 키워드 검색 요청이 들어온 경우 카카오 지도 API를 사용하여 위치 검색
const kakaoUrl = `https://dapi.kakao.com/v2/local/search/keyword.json?query=${query}`;
const kakaoSecretKey = process.env.KAKAO_ID;

const response = await axios.get(kakaoUrl, {
headers: {
Authorization: `KakaoAK ${kakaoSecretKey}`
}
});

// 키워드와 가장 근접한 장소의 위경도를 중심으로 설정
if (response.data.documents && response.data.documents.length > 0) {
const { x, y } = response.data.documents[0];
searchLongitude = parseFloat(x);
searchLatitude = parseFloat(y);
console.log('Updated Coordinates from Keyword:', searchLongitude, searchLatitude);
} else {
console.log('No results found for the query, using default coordinates.');
}
}

// 반경 내 포토부스 조회
const nearbyBooths = await Photobooth.findAll({
where: Sequelize.where(
Sequelize.fn(
'ST_Distance_Sphere',
Sequelize.literal(`POINT(${searchLongitude}, ${searchLatitude})`),
Sequelize.literal(`POINT(longitude, latitude)`)
),
{ [Op.lte]: radius }
)
});

req.nearbyBoothIds = nearbyBooths.map((booth) => booth.id); // 포토부스 ID 목록만 저장
console.log('Nearby Booth IDs:', req.nearbyBoothIds);
next();
} catch (error) {
console.error('Error fetching nearby booths:', error);
res.status(500).json({ message: '서버 오류가 발생했습니다.' });
}
};

module.exports = { getNearbyBooths };
9 changes: 9 additions & 0 deletions routes/albumRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const express = require('express');
const router = express.Router();
const { getNearbyBooths } = require('../middlewares/location');
const {getAlbum} = require('../controllers/albumController');

// 앨범 조회용 라우트
router.get('/:user_id', getNearbyBooths , getAlbum);

module.exports = router;
5 changes: 4 additions & 1 deletion routes/photoRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const express = require('express');
const router = express.Router();
const { uploadOneImageUrl, uploadOneImage } = require('../middlewares/s3');
const { uploadImageByQR } = require('../middlewares/uploadPhoto');
const { createTemp, updateInfo, updateRecord, savePhoto, deletePhoto } = require('../controllers/photoController');
const { createTemp, updateInfo, updateRecord, savePhoto, deletePhoto, getPhoto } = require('../controllers/photoController');

// 사진 등록용 라우트 1: 사용자id와 사진url 저장 (photoTemp 테이블)
router.post('/temp/upload/qr', uploadImageByQR, uploadOneImageUrl, createTemp); // 1) QR 업로드
Expand All @@ -20,4 +20,7 @@ router.post('/save/:photoTemp_id', savePhoto);
// 사진 삭제용 라우트
router.delete('/delete/:photo_id', deletePhoto);

// 사진 조회용 라우트
router.get('/:photo_id', getPhoto);

module.exports = router;

0 comments on commit a354284

Please sign in to comment.