File size: 4,835 Bytes
97f53b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
170
171
172
173
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const multer = require('multer');
const User = require('../Database/models/user');
const Post = require('../Database/models/newPost');
const Comment = require('../Database/models/comments');
const response = require('../utils/responseModel');



//Disk storage where image store
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/fruits');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});

//Check the image formate
const fileFilter = (req, file, cb) => {
    // reject a file
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image/jpg') {
        cb(null, true);
    } else {
        cb(null, false);
    }
};

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 10
    },
    fileFilter: fileFilter
});

router.post('/create', upload.single('file'), async (req, res, next) => {
    console.log(req.body);
    const userData = await User.findOne({ unique_id: req.body.userId }).exec();
    if (!userData) {
        res.send(response.failedResponse('Data not found!'))
    } else {
        console.log(" Data => " + userData)

        Post.findOne({ _id: req.body.postId }, function (err, postData) {
            if (!postData) {
                res.status(500).json({ error: 'Post not found!' });
            } else {
                var comment = Comment({
                    user: userData,
                    post: postData,
                    userId: req.body.userId,
                    comment: req.body.comment,
                    likes: userData
                })

                comment.save()
                    .then((post) => {
                        res.status(200).json(post);
                    })
                    .catch((error) => {
                        res.status(500).json({ error: 'An error occurred while creating the post.' });
                    });

            }

        });
    }
});

router.get('/:id', async (req, res, next) => {
    const postData = await Post.findOne({ _id: req.params.id }).exec();
    if (!postData) {
        res.status(500).json({ error: 'Post not found!' });
    } else {
        const comments = await Comment.find({ post: postData })
            .sort({ createdAt: 'descending' });
        if (!comments) {
            res.status(500).json({ error: 'Comments not found!' });
        } else {
            res.status(200).json({
                status: 'success',
                count: comments.length,
                comments,
            });
        }
    }
});

router.get('/byId', async (req, res, next) => {
    const post = await Post.findById(req.params.id).populate({
        path: 'profile',
        select: '-bio -website -user -_v',
    });

    if (!post) {
        return next(new AppError('Post not found', 400));
    }

    res.status(200).json({
        status: 'success',
        post,
    });
});

router.delete('/', async (req, res, next) => {
    //const post = await Post.deleteOne({ _id: req.params.id });
    const post = await Post.findById(req.params.id);
    if (!post) {
        return next(new AppError('Post not found', 400));
    }
    //  console.log(post, post.user.toString() === req.user.id)
    if (post.user.toString() !== req.user.id) {
        return next(
            new AppError('You are not authorized to delete this post', 401)
        );
    }

    post.commentsPost.length &&
        (await Comment.findByIdAndDelete(post.commentsPost[0]._id));

    await post.remove();

    res.status(200).json({
        message: 'deleted',
    });
});

router.post('/like', async (req, res, next) => {
    const post = await Post.findById(req.params.id).populate('profile');

    if (!post) {
        return next(new AppError('Post not found', 400));
    }
    const id = await post.getProfileId(req.user.id);

    if (post.likes.includes(id)) {
        const index = post.likes.indexOf(id);
        post.likes.splice(index, 1);
        await post.save((err) => {
            console.log(err);
        });
        await Notification.deleteMany({
            to: post.profile._id,
            user: id,
            type: 'Like',
        });
    } else {
        post.likes.push(id);
        await post.save();
    }

    res.status(200).json({
        status: 'success',
        post,
    });
});

router.delete('/:id', async (req, res) => {
    Comment.remove({ _id: req.params.id })
        .exec()
        .then(result => {
            res.status(200).send(response.successResponse(result));
        })
        .catch(error => {
            res.send(500).send(response.failedResponse(error))
        });
});

module.exports = router;