File size: 4,232 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
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 firebase = require("../utils/firebase");
const { successResponse, failedResponse } = require("../utils/responseModel");
var imageUrl = ""



//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);
    var image = [];
    await firebase.uploadFile(req.file.path, req.file.filename)
    await firebase.generateSignedUrl(req.file.filename).then(res => {
        imageUrl = res
    })

    if (imageUrl == "") {
        imageUrl = req.file.path
    }

    try {
        const data = await User.findOne({ unique_id: req.body.userId });
        if (!data) {
            res.send(failedResponse('Data not found!'))
        } else {
            console.log(" Data => " + data)
            const newPost = await Post.create({
                user: data,
                image: imageUrl,
                caption: req.caption,
                location: req.location,
                likes: data,
                profile: data,
            }).then(result => {
                res.status(200).send(successResponse(newPost));
            }).catch(error => {
                res.status(500).send(failedResponse(error));
            });
        }
    } catch (e) {

    }

});

router.get('/', async (req, res, next) => {
    const posts = await Post.find({})
        .sort({ createdAt: 'descending' })
        .populate('user');
    // const populatedPost = await posts.populate('profile').execPopulate();
    res.status(200).json({
        status: 'success',
        count: posts.length,
        posts,
    });
});

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,
    });
});

module.exports = router;