-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathus1.js
224 lines (199 loc) · 7.16 KB
/
us1.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
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// us1.js
import { MongoClient, ServerApiVersion } from 'mongodb';
import express from 'express';
import bodyParser from 'body-parser';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
app.use(bodyParser.json());
const uri = process.env.MongoURI;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
app.post('/test', async (req, res) => {
console.log('Request received:', req.body);
try {
res.status(200).json({message: 'Test data received successfully'});
} catch (error) {
console.error('Error:', error);
res.status(500).json({error: error.message});
}
});
app.post('/testMongo', async (req, res) => {
console.log('Request received:', req.body);
try {
await client.connect();
const database = client.db('userData');
const collection = database.collection('user');
const testDoc = await collection.findOne({});
if (testDoc) {
res.status(200).json({ message: 'MongoDB request succeeded', data: testDoc });
} else {
res.status(404).json({ message: 'No documents found' });
}
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/storeYoutubeData', async (req, res) => {
const {user, youtubeData} = req.body;
let collection;
await client.connect();
const db = client.db('userData');
collection = db.collection('user');
if (!collection) {
res.status(500).json({error: 'DB connection not established'});
return;
}
try {
const existingUser = await collection.findOne({ "user.user.id": user.user.id });
if (existingUser) {
res.status(200).json({ message: 'User already exists, welcome' });
// add func to track how many times the user has logged in
} else {
// User does not exist - insert a new document
const result = await collection.insertOne({user, youtubeData});
res.status(200).json({message: 'YoutubeData stored '});
}
} catch (error) {
console.error('Error storing data:', error);
res.status(500).json({error: error.message});
}
});
app.post('/storeLikes', async (req, res) => {
try {
const likesData = req.body.likes; // Assuming likes is an array of video data
await client.connect();
const database = client.db('userData');
const collection = database.collection('videoPosts');
// Create bulk operations
const bulkOps = likesData.map(likeData => {
return {
updateOne: {
filter: {
userId: likeData.userId,
"video.videoId": likeData.video.videoId
},
update: { $set: likeData },
upsert: true
}
};
});
await collection.bulkWrite(bulkOps);
res.status(200).json({ message: 'Likes stored/updated successfully' });
} catch (error) {
console.error('Error in bulk storing/updating likes:', error);
res.status(500).json({ error: error.message });
}
});
app.get('/homeFeed', async (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 15;
const skip = (page - 1) * limit; // Calculate the number of documents to skip for pagination
try {
await client.connect();
const database = client.db('userData');
const collection = database.collection('videoPosts');
const data = await collection.find({})
.sort({ likedAt: -1 })
.skip(skip)
.limit(limit)
.toArray();
// Check if there is more data to send for the next page
const totalCount = await collection.countDocuments();
const isMore = skip + data.length < totalCount;
res.status(200).json({ data, isMore });
} catch (error) {
console.error('Error retrieving data:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/likePost', async (req, res) => {
const { userId, videoId } = req.body;
try {
await client.connect();
const database = client.db('userData');
const videoPostsCollection = database.collection('videoPosts');
const likedPostsCollection = database.collection('likedPosts');
// Check if the user already liked the post
const existingLike = await likedPostsCollection.findOne({ userId, videoId });
if (existingLike) {
return res.status(409).json({ message: 'User already liked this post' });
}
// Add the new like to likedPosts collection
await likedPostsCollection.insertOne({ userId, videoId, createdAt: new Date() });
// Increment the like count for the video in videoPosts collection
const updateResult = await videoPostsCollection.updateOne(
{ videoId: videoId },
{ $inc: { likeCount: 1 }, $addToSet: { likedPosts: userId } } // Increment the likeCount and add userId to likedPosts
);
if (updateResult.modifiedCount > 0) {
res.status(200).json({ message: 'Successfully liked the post' });
} else {
res.status(400).json({ message: 'Failed to like the post' });
}
} catch (error) {
console.error('Error liking post:', error);
res.status(500).json({ error: error.message });
} finally {
client.close();
}
});
app.get('/likes', async (req, res) => {
const { videoId } = req.query;
try {
await client.connect();
const database = client.db('userData');
const videoPosts = database.collection('videoPosts');
const videoPost = await videoPosts.findOne({ videoId: videoId }, { projection: { likeCount: 1 } });
res.status(200).json({ videoId, likesCount: videoPost ? videoPost.likeCount : 0 });
} catch (error) {
console.error('Error fetching likes:', error);
res.status(500).json({ error: error.message });
} finally {
client.close();
}
});
app.post('/commentPost', async (req, res) => {
const { userId, videoId, comment } = req.body;
try {
await client.connect();
const database = client.db('userData');
const collection = database.collection('commentsCollection');
const result = await collection.insertOne({ userId, videoId, comment, createdAt: new Date() });
if (result.insertedId) {
res.status(200).json({ message: 'Successfully commented on the post' });
} else {
res.status(400).json({ message: 'Failed to comment on the post' });
}
} catch (error) {
console.error('Error commenting on post:', error);
res.status(500).json({ error: error.message });
} finally {
client.close();
}
});
app.get('/comments', async (req, res) => {
const { videoId } = req.query;
try {
await client.connect();
const database = client.db('userData');
const collection = database.collection('commentsCollection');
const comments = await collection.find({ videoId }).sort({ createdAt: -1 }).toArray();
res.status(200).json({ videoId, comments });
} catch (error) {
console.error('Error fetching comments:', error);
res.status(500).json({ error: error.message });
} finally {
client.close();
}
});
app.listen(5000, () => {
console.log(`Server running on 5000`);
});