-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstoreController.js
67 lines (54 loc) · 1.94 KB
/
storeController.js
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
const mongoose = require('mongoose');
const Store = mongoose.model('Store');
const multer = require('multer');
const jimp = require('jimp');
const uuid = require('uuid');
const multerOptions = {
storage: multer.memoryStorage(),
fileFilter : function(req, file, next){
const isPhoto = file.mimetype.startsWith('image/');
if(isPhoto){
next(null, true);
} else {
next({message: 'That filetype isn\'t allowed!'}, false);
}
}
};
exports.homePage = (req, res) => {
res.render('index');
};
exports.addStore = (req, res) =>{
res.render('editStore', {title: 'Add Store'});
};
exports.upload = multer(multerOptions).single('photo');
exports.resize = async(req, res, next) => {
if(!req.file){
next();
return;
}
const extension = req.file.mimetype.split('/')[1];
req.body.photo = uuid.v4()+'.'+extension;
//resize
const photo = await jimp.read(req.file.buffer);
await photo.resize(800, jimp.AUTO);
await photo.write('./public/uploads/'+req.body.photo);
next();
};
exports.createStore = async (req, res) => {
const store = await (new Store(req.body)).save();
req.flash('success', 'Successfully Created '+store.name+'. Care to leave a review');
res.redirect('/store/'+store.slug);
};
exports.getStores = async (req, res) => {
const stores = await Store.find();
res.render('stores',{ title: 'Stores', stores });
};
exports.editStore = async (req, res) => {
const store = await Store.findOne({_id: req.params.id});
res.render('editStore', {title: 'Edit '+store.name, store});
};
exports.updateStore = async (req, res) => {
const store = await Store.findOneAndUpdate({_id: req.params.id}, req.body, {new: true, runValidators: true}).exec();
req.flash('success', 'Successfully updated <strong>' +store.name+ '</strong>. <a href="/stores/'+ store.slug+'">View Source -> </a>');
res.redirect('/stores/'+store._id+'/edit');
};