이승윤

feat: 카테고리 DB 연동 및 뷰 구현

......@@ -4,7 +4,8 @@ var Schema = mongoose.Schema;
var CategoriSchema = new Schema({
title: {
type: String,
required: [true, '카테고리명을 입력해주세요'],
default: 'default',
required: [true, '카테고리명이 비어있습니다!'],
},
videoNum: String,
description: String, //설명
......@@ -16,7 +17,7 @@ var CategoriSchema = new Schema({
});
CategoriSchema.virtual('getDate').get(function () {
var date = new Date(this.created_at);
var date = new Date(this.created_at);
return {
year: date.getFullYear(),
month: date.getMonth() + 1,
......@@ -24,4 +25,4 @@ CategoriSchema.virtual('getDate').get(function () {
};
});
module.exports = mongoose.model('categories', CategoriSchema);
\ No newline at end of file
module.exports = mongoose.model('categories', CategoriSchema);
......
......@@ -4,13 +4,12 @@ var youtube = new Youtube();
var express = require('express');
var router = express.Router();
var word = '백종원 레시피'; // 검색어 지정
var word = '백종원'; // 검색어 지정
var limit = 10; // 출력 갯수
var video = [];
var test = 'test';
var count = 0;
youtube.setKey('AIzaSyAsKr_oWGZIBbL5tLdIl98Lf9Pzqj8jX4o'); // API 키 입력
youtube.addParam('order', 'rating'); // 평점 순으로 정렬
youtube.addParam('type', 'video'); // 타입 지정
youtube.addParam('videoLicense', 'creativeCommon'); // 크리에이티브 커먼즈 아이템만 불러옴
......
var express = require('express');
var router = express.Router();
var CategoriModel = require('../models/CategoriModel');
var csrf = require('csurf');
var csrfProtection = csrf({ cookie: true });
//var csrf = require('csurf');
//var csrfProtection = csrf({ cookie: true });
var loginRequired = require('../libs/loginRequired');
var path = require('path');
......@@ -34,56 +34,43 @@ router.get('/', function (req, res) {
router.get('/products', function (req, res) {
CategoriModel.find(function (err, products) {
res.render(
'admin/products',
{ products: products }
'category/products',
{ categories: products }
//ProductModel의 products를 받아서
//categori/products로 response를 보낸다.
);
});
});
router.get(
'/products/write',
loginRequired,
csrfProtection,
function (req, res) {
//edit에서도 같은 form을 사용하므로 빈 변수( product )를 넣어서 에러를 피해준다
res.render('categori/form', { product: '', csrfToken: req.csrfToken() });
}
);
router.get('/categories/write', loginRequired, function (req, res) {
//edit에서도 같은 form을 사용하므로 빈 변수( product )를 넣어서 에러를 피해준다
res.render('category/form', { categories: '' });
});
router.post(
'/products/write',
upload.single('thumbnail'),
loginRequired,
csrfProtection,
function (req, res) {
var product = new CategoriModel({
name: req.body.name,
thumbnail: req.file ? req.file.filename : '',
price: req.body.price,
description: req.body.description,
username: req.user.username,
router.post('/categories/write', loginRequired, function (req, res) {
var category = new CategoriModel({
title: req.body.title,
description: req.body.description,
username: req.user.username,
});
//이 아래는 수정되지 않았음
var validationError = category.validateSync();
if (validationError) {
res.send(validationError);
} else {
category.save(function (err) {
res.redirect('/categori/products');
});
//이 아래는 수정되지 않았음
var validationError = product.validateSync();
if (validationError) {
res.send(validationError);
} else {
product.save(function (err) {
res.redirect('/categori/products');
});
}
//이 위는 수정되지 않았음
}
);
//이 위는 수정되지 않았음
});
router.get('/products/detail/:id', function (req, res) {
//url 에서 변수 값을 받아올떈 req.params.id 로 받아온다
CategoriModel.findOne({ id: req.params.id }, function (err, product) {
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
//제품정보를 받고 그안에서 댓글을 받아온다.
CategoriModel.find({ product_id: req.params.id }, function (err, comments) {
res.render('categori/productsDetail', {
res.render('category/productsDetail', {
product: product,
comments: comments,
});
......@@ -91,29 +78,23 @@ router.get('/products/detail/:id', function (req, res) {
});
});
router.get(
'/products/edit/:id',
loginRequired,
csrfProtection,
function (req, res) {
//기존에 폼에 value안에 값을 셋팅하기 위해 만든다.
CategoriModel.findOne({ id: req.params.id }, function (err, product) {
res.render('categori/form', {
product: product,
csrfToken: req.csrfToken(),
});
router.get('/products/edit/:id', loginRequired, function (req, res) {
//기존에 폼에 value안에 값을 셋팅하기 위해 만든다.
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
res.render('category/form', {
categories: product,
});
}
);
});
});
router.post(
'/products/edit/:id',
loginRequired,
upload.single('thumbnail'),
csrfProtection,
// csrfProtection,
function (req, res) {
//그전에 지정되 있는 파일명을 받아온다
CategoriModel.findOne({ id: req.params.id }, function (err, product) {
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
//아래의 코드만 추가되면 된다.
if (req.file && product.thumbnail) {
//요청중에 파일이 존재 할시 이전이미지 지운다.
......@@ -131,7 +112,7 @@ router.post(
{ id: req.params.id },
{ $set: query },
function (err) {
res.redirect('/categori/products/detail/' + req.params.id);
res.redirect('/category/products/detail/' + req.params.id);
}
);
});
......@@ -139,7 +120,7 @@ router.post(
);
router.get('/products/delete/:id', function (req, res) {
CategoriModel.remove({ id: req.params.id }, function (err) {
CategoriModel.deleteMany({ _id: req.params.id }, function (err) {
res.redirect('/categori/products');
});
});
......@@ -159,7 +140,7 @@ router.post('/products/ajax_comment/insert', function (req, res) {
});
router.post('/products/ajax_comment/delete', function (req, res) {
CategoriModel.remove({ id: req.body.comment_id }, function (err) {
CategoriModel.remove({ _id: req.body.comment_id }, function (err) {
res.json({ message: 'success' });
});
});
......
......@@ -10,7 +10,7 @@
</div>
<div class="panel-body">
<form role="form" action="" id="login_form" method="post">
QKQKQfieldset>
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="ID" name="username" type="text" autofocus="" required="">
</div>
......
<% include ../includes/header.ejs %>
<form action="" method="post" >
<table class="table table-bordered">
<tr>
<th>카테고리명</th>
<td><input type="text" name="title" class="form-control" value="<%=categories.title%>"/></td>
</tr>
<tr>
<th>설명</th>
<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">
</form>
<% include ../includes/footer.ejs %>
\ No newline at end of file
<% include ../includes/header.ejs %>
<table class="table table-bordered table-hover">
<tr>
<th width="100px" style="text-align: center;">카테고리명</th>
<th style="text-align: center;">개설 날짜</th>
<th>내용</th>
<th>사용자명</th>
<th>삭제</th>
</tr>
<%categories.forEach(function(product){%>
<tr>
<td>
<a href="/categori/products/detail/<%=product.id%>"><%=product.title%></a>
</td>
<td>
<%=product.getDate.year%> -
<%=product.getDate.month%> -
<%=product.getDate.day%>
</td>
<td>
<%=product.description%> -
</td>
<td>
<%=product.username%> -
</td>
<td>
<a href="/categori/products/delete/<%=product.id%>" class="btn btn-danger" onclick="return confirm('삭제하시겠습니까?')">삭제</a>
</td>
</tr>
<% }); %>
</table>
<a href="categori/write" class="btn btn-default">작성하기</a>
<% include ../includes/footer.ejs %>
\ No newline at end of file
<% include ../includes/header.ejs %>
<div class="panel panel-default">
<div class="panel-heading">
<%=product.title%>
</div>
<div class="panel-body">
<div style="padding-bottom: 10px">
작성일 :
<%=product.getDate.year%> -
<%=product.getDate.month%> -
<%=product.getDate.day%>
</div>
<% if(product.thumbnail){%>
<p>
<img src="/uploads/<%=product.thumbnail%>" style="max-width: 100%"/>
</p>
<% } %>
<%=product.description%>
<!-- 댓글영역 -->
<div>
댓글작성하기
<form id="commentForm" action="" method="post">
<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>
</form>
</div>
<!-- 댓글영역 -->
<hr />
<div id="comment_area">
<% comments.forEach(function(comment){ %>
<div>
<%=comment.content%>
( <a class='comment_delete' comment_id='<%=comment._id%>'>삭제</a> )
</div>
<% }); %>
</div>
</div>
</div>
<a href="/categori/products" class="btn btn-default">목록으로</a>
<a href="/categori/products/edit/<%=product._id%>" class="btn btn-primary">수정</a>
<% include ../includes/footer.ejs %>
<script>
(function(){
$(document).ready(function() {
$('#commentForm').submit(function(){
var $contentVal = $(this).children('textarea[name=content]').val();
if($contentVal){
$.ajax({
url: '/admin/products/ajax_comment/insert',
type: 'POST',
data: $(this).serialize(),
})
.done(function(args) {
if(args.message==="success"){
$('#comment_area').append(
'<div>' + args.content +
" ( <a class='comment_delete' comment_id='"+ args._id +"'>삭제</a> ) </div>"
);
$('#commentForm textarea[name=content]').val("");
}
})
.fail(function(args) {
console.log(args);
});
}else{
alert('댓글 내용을 입력해주세요.')
}
return false;
});
});
})();
</script>
<script>
$(document).on('click' , '.comment_delete' , function(){
if(confirm('삭제하시겠습니까?')){ //확인창 예 눌렀을 시만 진행
var $self = $(this);
$.ajax({
url: '/admin/products/ajax_comment/delete',
type: 'POST',
data: { comment_id : $self.attr('comment_id') },
})
.done(function() {
$self.parent().remove();
alert("삭제가 완료되었습니다.");
})
.fail(function(args) {
console.log(args);
});
}
});
</script>
\ No newline at end of file
<% include ./includes/header.ejs %>
<div class="container" id="masonry_container">
<div id="masonry_container">
한식
<% for (var i in videos) { %>
<div id="<%=videos[i].id%>" vid="<%=videos[i].video_id%>">
</div>
......