이승윤

feat: categori detail 쿼리 추가 기능

var express = require('express');
var router = express.Router();
var CategoriModel = require('../models/CategoriModel');
//var csrf = require('csurf');
//var csrfProtection = csrf({ cookie: true });
var loginRequired = require('../libs/loginRequired');
var path = require('path');
var uploadDir = path.join(__dirname, '../uploads'); // 루트의 uploads위치에 저장한다.
var fs = require('fs');
var VideoModel = require('../models/VideoModel');
var Youtube = require('youtube-node');
var youtube = new Youtube();
//multer 셋팅
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
//이미지가 저장되는 도착지 지정
callback(null, uploadDir);
},
filename: function (req, file, callback) {
// products-날짜.jpg(png) 저장
callback(
null,
'products-' + Date.now() + '.' + file.mimetype.split('/')[1]
);
},
});
var loginRequired = require('../libs/loginRequired');
var upload = multer({ storage: storage });
var limit = 10; // 출력 갯수
youtube.setKey('AIzaSyCAaeW1qMSInEdN1OzU20FZlToIZYkb1bc'); // API 키 입력
router.get('/', function (req, res) {
res.send('categori main page');
......@@ -43,7 +26,6 @@ router.get('/products', function (req, res) {
});
router.get('/categories/write', loginRequired, function (req, res) {
//edit에서도 같은 form을 사용하므로 빈 변수( product )를 넣어서 에러를 피해준다
res.render('category/form', { categories: '' });
});
......@@ -67,15 +49,83 @@ router.post('/categories/write', loginRequired, function (req, res) {
router.get('/products/detail/:id', function (req, res) {
//url 에서 변수 값을 받아올떈 req.params.id 로 받아온다
var word = req.query.keyword;
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
var video = [];
//제품정보를 받고 그안에서 댓글을 받아온다.
CategoriModel.find({ product_id: req.params.id }, function (err, comments) {
if (word != null) {
var count = 0;
youtube.addParam('order', 'rating'); // 평점 순으로 정렬
youtube.addParam('type', 'video'); // 타입 지정
youtube.addParam('videoLicense', 'creativeCommon'); // 크리에이티브 커먼즈 아이템만 불러옴
youtube.search(word, limit, function (err, result) {
// 검색 실행
console.log(word);
if (err) {
console.log(err);
} // 에러일 경우 에러공지하고 빠져나감
//console.log(JSON.stringify(result, null, 2)); // 받아온 전체 리스트 출력
var items = result['items']; // 결과 중 items 항목만 가져옴
for (var i in items) {
var it = items[i];
for (var j in it) {
if (it[j]['title'] != null) {
var title = it[j]['title'];
}
if (it[j]['videoId'] != null) {
var video_id = it[j]['videoId'];
}
var urls = 'https://www.youtube.com/watch?v=' + video_id;
}
var item = {
id: count,
title: title,
video_id: video_id,
urls: urls,
categori: product.title,
};
count++;
video.push(item);
}
res.render('category/productsDetail', {
product: product,
comments: comments,
videos: video,
});
});
} else {
res.render('category/productsDetail', {
product: product,
comments: comments,
videos: video,
});
}
});
});
});
router.post('/products/detail/:id', loginRequired, function (req, res) {
var item = [];
var count = 1;
for (var i in req.body.videoNum) {
item.push(req.body.videoNum[i].split('///'));
var video = new VideoModel({
categori: item[i][2],
id: count,
title: item[i][1],
video_id: item[i][3],
urls: item[i][4],
});
var validationError = video.validateSync();
if (validationError) {
res.send(validationError);
} else {
video.save(function (err) {});
}
count++;
}
res.redirect('/categori/products');
});
router.get('/products/edit/:id', loginRequired, function (req, res) {
......@@ -87,21 +137,9 @@ router.get('/products/edit/:id', loginRequired, function (req, res) {
});
});
router.post(
'/products/edit/:id',
loginRequired,
upload.single('thumbnail'),
// csrfProtection,
function (req, res) {
router.post('/products/edit/:id', loginRequired, function (req, res) {
//그전에 지정되 있는 파일명을 받아온다
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
//아래의 코드만 추가되면 된다.
if (req.file && product.thumbnail) {
//요청중에 파일이 존재 할시 이전이미지 지운다.
fs.unlinkSync(uploadDir + '/' + product.thumbnail);
}
//위의 코드만 추가되면 된다.
//넣을 변수 값을 셋팅한다
var query = {
name: req.body.name,
thumbnail: req.file ? req.file.filename : product.thumbnail,
......@@ -112,12 +150,11 @@ router.post(
{ id: req.params.id },
{ $set: query },
function (err) {
res.redirect('/category/products/detail/' + req.params.id);
res.redirect('/categori/products/detail/' + req.params.id);
}
);
});
}
);
});
router.get('/products/delete/:id', function (req, res) {
CategoriModel.deleteMany({ _id: req.params.id }, function (err) {
......
......@@ -10,6 +10,6 @@
<td><input type="text" name="description" class="form-control" value="<%=categories.description%>"/></td>
</tr>
</table>
<input type="submit" name="submit" value="submit" class="btn btn-primary">
<input type="submit" name="submit" value="완료" class="btn btn-primary">
</form>
<% include ../includes/footer.ejs %>
\ No newline at end of file
......
......@@ -3,6 +3,32 @@
<div class="panel-heading">
<%=product.title%>
</div>
<form method="get" action="">
<div class="input-group">
<input type="text" class="form-control" placeholder="검색 키워드를 입력하세요!" name="keyword" autocomplete='off'>
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">찾기</button>
</span>
</div>
</form>
<form method="post" action="">
<% for (var i in videos) { %>
<div style="float:left;
padding: 15px;
">
<input type="checkbox" name="videoNum" style="
position: absolute;
margin-top: 5px;
margin-left: 5px;
z-index: 4;
zoom:3.0;
" value="<%=videos[i].id + '///' + videos[i].title +'///'+ videos[i].categori +'///'+ videos[i].video_id +'///'+ videos[i].urls%>"/>
<div id="<%=videos[i].id%>" vid="<%=videos[i].video_id%>">
</div>
</div>
<%};%>
<button class="btn btn-primary" style="margin-top: 10px; margin-left: 15px;" >영상담기</button>
</form>
<div class="panel-body">
<div style="padding-bottom: 10px">
작성일 :
......@@ -20,9 +46,9 @@
<div>
댓글작성하기
<form id="commentForm" action="" method="post">
<input type="hidden" name="product_id" value="<%=product._id%>" />
<input type="hidden" name="product_id" value="<%=product.id%>" />
<textarea class="form-control" name="content"></textarea>
<button class="btn btn-primary" style="margin-top: 10px">댓글작성</button>
<button class="btn btn-primary" style="margin-top: 10px" type="submit">댓글작성</button>
</form>
</div>
<!-- 댓글영역 -->
......@@ -91,3 +117,44 @@ $(document).on('click' , '.comment_delete' , function(){
}
});
</script>
<script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.1/imagesloaded.pkgd.min.js"></script>
<script type="text/javascript">
var $masonry_container = $('#masonry_container');
$masonry_container.imagesLoaded(function () {
$masonry_container.masonry({
itemSelector: '.masonry-grid',
columnWidth: 270
});
});
</script>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var players = [];
var videoIds = [];
for (var i = 0; i < 10; i++) {
players.push(String(i));
videoIds.push($('#' + i).attr('vid'));
}
function onYouTubeIframeAPIReady() {
for (var i = 0; i < videoIds.length; i++) {
player = new YT.Player(players[i], {
height: '300',
width: '500',
videoId: videoIds[i],
events: {
// 'onReady': onPlayerReady,
// 'onStateChange': onPlayerStateChange
}
});
}
}
</script>
\ No newline at end of file
......