const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require ('path');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
}
});
const uploadImg = multer({
storage: storage,
fileFilter : (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
console.log('only jpeg and png are accepted!!!')
cb(null, false)
}
},
limits: {
fileSize: 1024 * 1024 * 5
},
}
).single('image');
const {Posts} = require('../models/Posts');
// Get All post
router.get('/posts', (req, res, next) => {
Posts.find({}, (err, data) => {
if (!err) {
res.send(data);
} else {
console.log(err);
}
});
});
router.post('/posts/add', uploadImg, (req, res, next) => {
if (!req.file) return res.send('Please upload a file');
console.log(req.body);
const pos = new Posts({
title: req.body.title,
image: req.file.filename,
HeadingTitle: req.body.HeadingTitle,
datetime: req.body.datetime,
smallTitle: req.body.smallTitle,
MoviesContent: req.body.MoviesContent,
DownloadLinkButtonsHeading: req.body.DownloadLinkButtonsHeading,
Buttons: req.body.Buttons,
allCategories: req.body.allCategories,
});
pos.save((err, data) => {
const image = `http://localhost:5000/${req.file.filename}`
res.status(200).json({
code: 200, message: 'post Added Sucessfully',
addPosts: data,
image: image
})
})
});
// Get Single ID
router.get('/posts/:id', (req, res, next) => {
Posts.findById(req.params.id, (err, data) => {
if (!err) {
res.send(data);
} else {
console.log(err);
}
});
});
// Update post
router.put('/posts/edit/:id', (req, res, next) => {
if (!req.file) return res.send('Please upload a file');
const pos = {
post: req.body,
title: req.body.title,
image: req.file.filename,
HeadingTitle: req.body.HeadingTitle,
datetime: req.body.datetime,
smallTitle: req.body.smallTitle,
MoviesContent: req.body.MoviesContent,
DownloadLinkButtonsHeading: req.body.DownloadLinkButtonsHeading,
Buttons: req.body.Buttons,
allCategories: req.body.allCategories,
};
Posts.findByIdAndUpdate(req.params.id, { $set: pos }, { new: true }, (err, data) => {
if (!err) {
res.status(200).json({
code: 200, message: 'post Updated Successfully',
updatePosts: data
})
} else {
console.log(err);
}
});
});
// Delete post
router.delete('/posts/:id', (req, res, next) => {
Posts.findByIdAndRemove(req.params.id, (err, data) => {
if (!err) {
res.status(200).json({
code: 200, message: 'post Deleted Successfully',
deletePosts: data
});
} else {
console.log(err);
}
});
})
module.exports = router