-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostRouter.js
144 lines (131 loc) · 3.79 KB
/
postRouter.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
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
'use strict'
const express = require('express');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const _ = require('lodash');
const router = express.Router();
const bodyParser = require('body-parser');
const jsonParser = bodyParser.json();
const multer = require('multer');
const path = require('path');
const moment = require('moment');
const cloudinary = require('cloudinary');
const cloudinaryStorage = require('multer-storage-cloudinary');
const config = require('./config');
const {Post} = require('./models');
function checkFileType(file, callback) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname) {
return callback(null, true);
} else {
callback('Error: Images Only!');
}
}
// Default upload multer disk storage
let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public/uploads/');
},
filename: function(req, file, callback) {
callback(null, Date.now()+file.originalname);
}
})
// use upload cloudinary storage if possible
if (config.cloudinary
&& config.cloudinary.apiKey
&& config.cloudinary.apiSecret) {
cloudinary.config({
cloud_name: config.cloudinary.cloudName,
api_key: config.cloudinary.apiKey,
api_secret: config.cloudinary.apiSecret
});
storage = cloudinaryStorage({
cloudinary: cloudinary,
folder: 'uploads',
allowedFormats: ['jpg', 'png', 'jpeg', 'gif'],
filename: function(req, file, callback) {
callback(undefined, Date.now()+file.originalname)
}
})
}
const upload = multer({
storage: storage,
fileFilter: function(req, file, callback) {
checkFileType(file, callback)
}
})
// GET Endpoints
router.get('/', (req, res) => {
Post
.find()
.then(posts => {
res.json(
_.orderBy(posts, post => moment(post.created, 'MMM Do YYYY'), 'desc')
.map(post => post.serialize())
);
})
.catch(err => {
console.error(err);
res.status(500).json({ error: 'something is not right' });
});
});
router.get('/:id', function (req, res) {
Post
.findById(req.params.id, function (err, post) {
if (err) return res.status(500).send('something went wrong trying to find this post.');
if (!post) return res.status(404).send('no post found.');
res.status(200).send(post);
});
});
// POST Endpoints
router.post('/', upload.single('postImg'), (req, res) => {
if (!req.body || !req.body.text || !req.file) {
const message = `Missing text and/or file in request body`;
console.error(message);
return res.status(400).send(message);
}
Post.create({
image: req.file.url || req.file.path,
created: moment().format('MMM Do YYYY'),
text: req.body.text
})
.then(res.redirect('/'))
.catch(err => {
console.error(err);
res.status(500).json({ error: 'Something went wrong' });
});
});
// PATCH Endpoints
router.patch('/:id', jsonParser, (req, res) => {
if (!req.body.text) {
const message = `Missing text in request body`;
console.error(message);
return res.status(400).send(message);
}
console.log(`Updating post\`${req.params.id}\``);
return Post.findByIdAndUpdate(req.params.id, {
$set: {
text: req.body.text
}
})
.then(result => {
console.log(`result: ${JSON.stringify(result, null, 2)}`)
return res.status(204).end();
})
});
// DELETE Endpoints
router.delete('/:id', (req, res) => {
Post
.findByIdAndRemove(req.params.id)
.then(() => {
res.status(204).json({ message: 'Success' });
})
.catch(err => {
console.error(err);
res.status(500).json({ error: 'Something went wrong' });
});
});
// Export router for use in server.js
module.exports = {router};