index.js
4.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const schedule = require('node-schedule');
const { Good, Auction, User, sequelize } = require('../models');
const { isLoggedIn, isNotLoggedIn } = require('./middlewares');
const router = express.Router();
router.use((req, res, next) => {
res.locals.user = req.user;
next();
});
router.get('/', async (req, res, next) => {
try {
const goods = await Good.findAll({ where: { soldId: null } });
res.render('main', {
title: 'NodeAuction',
goods,
loginError: req.flash('loginError'),
});
} catch (error) {
console.error(error);
next(error);
}
});
router.get('/join', isNotLoggedIn, (req, res) => {
res.render('join', {
title: '회원가입 - NodeAuction',
joinError: req.flash('joinError'),
});
});
router.get('/good', isLoggedIn, (req, res) => {
res.render('good', { title: '상품 등록 - NodeAuction' });
});
fs.readdir('uploads', (error) => {
if (error) {
console.error('uploads 폴더가 없어 uploads 폴더를 생성합니다.');
fs.mkdirSync('uploads');
}
});
const upload = multer({
storage: multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads/');
},
filename(req, file, cb) {
const ext = path.extname(file.originalname);
cb(null, path.basename(file.originalname, ext) + new Date().valueOf() + ext);
},
}),
limits: { fileSize: 5 * 1024 * 1024 },
});
router.post('/good', isLoggedIn, upload.single('img'), async (req, res, next) => {
try {
const { name, price } = req.body;
const good = await Good.create({
ownerId: req.user.id,
name,
img: req.file.filename,
price,
});
const end = new Date();
end.setDate(end.getDate() + 1); // 하루 뒤
schedule.scheduleJob(end, async () => {
const success = await Auction.find({
where: { goodId: good.id },
order: [['bid', 'DESC']],
});
await Good.update({ soldId: success.userId }, { where: { id: good.id } });
await User.update({
money: sequelize.literal(`money - ${success.bid}`),
}, {
where: { id: success.userId },
});
});
res.redirect('/');
} catch (error) {
console.error(error);
next(error);
}
});
router.get('/good/:id', isLoggedIn, async (req, res, next) => {
try {
const [good, auction] = await Promise.all([
Good.find({
where: { id: req.params.id },
include: {
model: User,
as: 'owner',
},
}),
Auction.findAll({
where: { goodId: req.params.id },
include: { model: User },
order: [['bid', 'ASC']],
}),
]);
res.render('auction', {
title: `${good.name} - NodeAuction`,
good,
auction,
auctionError: req.flash('auctionError'),
});
} catch (error) {
console.error(error);
next(error);
}
});
router.post('/good/:id/bid', isLoggedIn, async (req, res, next) => {
try {
const { bid, msg } = req.body;
const good = await Good.find({
where: { id: req.params.id },
include: { model: Auction },
order: [[{ model: Auction }, 'bid', 'DESC']],
});
if (good.price > bid) { // 시작 가격보다 낮게 입찰하면
return res.status(403).send('시작 가격보다 높게 입찰해야 합니다.');
}
// 경매 종료 시간이 지났으면
if (new Date(good.createdAt).valueOf() + (24 * 60 * 60 * 1000) < new Date()) {
return res.status(403).send('경매가 이미 종료되었습니다');
}
// 직전 입찰가와 현재 입찰가 비교
if (good.auctions[0] && good.auctions[0].bid >= bid) {
return res.status(403).send('이전 입찰가보다 높아야 합니다');
}
const result = await Auction.create({
bid,
msg,
userId: req.user.id,
goodId: req.params.id,
});
req.app.get('io').to(req.params.id).emit('bid', {
bid: result.bid,
msg: result.msg,
nick: req.user.nick,
});
return res.send('ok');
} catch (error) {
console.error(error);
return next(error);
}
});
router.get('/list', isLoggedIn, async (req, res, next) => {
try {
const goods = await Good.findAll({
where: { soldId: req.user.id },
include: { model: Auction },
order: [[{ model: Auction }, 'bid', 'DESC']],
});
res.render('list', { title: '낙찰 목록 - NodeAuction', goods });
} catch (error) {
console.error(error);
next(error);
}
});
module.exports = router;