-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
341 lines (324 loc) · 10.8 KB
/
app.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
const express = require("express");
const app = express();
app.use(express.json());
const bcrypt = require("bcrypt");
const sqlite3 = require("sqlite3");
const { open } = require("sqlite");
const jwt = require("jsonwebtoken");
const path = require("path");
const dbPath = path.join(__dirname, "/twitterClone.db");
let db = null;
const secretKey = "!@#$%^&*";
const setUpDatabaseConnection = async () => {
try {
db = await open({
filename: dbPath,
driver: sqlite3.Database,
});
app.listen(3000, () => {
console.log("server is listening on port 3000");
});
} catch (e) {
console.log(e.message);
process.exit(1);
}
};
setUpDatabaseConnection();
//api 1
app.post("/register/", async (req, res) => {
const { username, password, name, gender } = req.body;
const bringUserQuery = `select * from User where username like '${username}'`;
const dbUser = await db.get(bringUserQuery);
if (dbUser !== undefined) {
res.status(400);
res.send("User already exists");
} else if (password.length < 6) {
res.status(400);
res.send("Password is too short");
} else {
const hashedPassword = await bcrypt.hash(password, 10);
console.log(hashedPassword);
const registerQuery = `
INSERT INTO User (username, password, name, gender)
VALUES( '${username}', '${hashedPassword}', '${name}', '${gender}');`;
await db.run(registerQuery);
res.send("User created successfully");
}
});
//api 2
app.post("/login/", async (req, res) => {
const { username, password } = req.body;
const bringUserQuery = `select * from User where username like '${username}'`;
const dbUser = await db.get(bringUserQuery);
if (dbUser === undefined) {
res.status(400);
res.send("Invalid user");
} else {
const isPasswordMatched = await bcrypt.compare(password, dbUser.password);
if (isPasswordMatched) {
const payload = {
username: username,
};
const jwtToken = jwt.sign(payload, secretKey);
res.json({ jwtToken });
} else {
res.status(400);
res.send("Invalid password");
}
}
});
//middleware
const authenticationFunction = (req, res, next) => {
const authHeader = req.headers["authorization"];
let jwtToken;
if (authHeader !== undefined) {
jwtToken = authHeader.split(" ")[1];
}
if (jwtToken === undefined) {
res.status(401);
res.send("Invalid JWT Token");
} else {
jwt.verify(jwtToken, secretKey, async (error, payLoad) => {
if (error) {
res.status(401);
res.send("Invalid JWT Token");
} else {
const { username } = payLoad;
req.username = username;
next();
}
});
}
};
//api 3
app.get("/user/tweets/feed/", authenticationFunction, async (req, res) => {
const username = req.username;
const bringUserQuery = `
select * from User where username like '${username}';`;
const dbUser = await db.get(bringUserQuery);
console.log(dbUser);
const { user_id } = dbUser;
const bringAllLatestTweets = `
select username, tweet ,
date_time as dateTime from Tweet inner join User on
Tweet.user_id = User.user_id where Tweet.user_id in
(select following_user_id from Follower
where follower_user_id like ${user_id})
order by date_time desc limit 4;`;
const tweetList = await db.all(bringAllLatestTweets);
res.json(tweetList);
});
//api 4
app.get("/user/following/", authenticationFunction, async (req, res) => {
const username = req.username;
const bringUserQuery = `
select * from User where username like '${username}';`;
const dbUser = await db.get(bringUserQuery);
console.log(dbUser);
const { user_id } = dbUser;
const bringAllWhomeUserFollowing = `
select name from User
where user_id in (
select following_user_id from Follower where
Follower.follower_user_id like '${user_id}'
)`;
const data = await db.all(bringAllWhomeUserFollowing);
res.json(data);
});
//api 5
app.get("/user/followers/", authenticationFunction, async (req, res) => {
const username = req.username;
const bringUserQuery = `
select * from User where username like '${username}';`;
const dbUser = await db.get(bringUserQuery);
console.log(dbUser);
const { user_id } = dbUser;
const bringAllFollowers = `
select name from User
where user_id in (
select follower_user_id from Follower where
Follower.following_user_id like '${user_id}'
);`;
const data = await db.all(bringAllFollowers);
res.json(data);
});
//api 6
app.get("/tweets/:tweetId/", authenticationFunction, async (req, res) => {
const { tweetId } = req.params;
const requiredTweetQuery = `select * from Tweet where tweet_id = ${tweetId};`;
const requiredTweet = await db.get(requiredTweetQuery);
console.log(requiredTweet);
const { user_id } = requiredTweet;
const username = req.username;
const bringUserId = `
select user_id from User where username like '${username}';`;
let user_id_WhichRequested = await db.get(bringUserId);
user_id_WhichRequested = user_id_WhichRequested.user_id;
console.log(user_id_WhichRequested);
const FollowingsListOfUser = `
select following_user_id from Follower where
follower_user_id = ${user_id_WhichRequested};`;
let followingList = await db.all(FollowingsListOfUser);
console.log(followingList);
let followingList2 = followingList.map((each) => each.following_user_id);
console.log(followingList2);
if (user_id in followingList2) {
const QueryForTweet = `select tweet, date_time from
Tweet where tweet_id = ${tweetId}`;
const QueryForReplies = `
select count(reply_id) as replies
from (Tweet inner join Reply on Tweet.tweet_id = Reply.tweet_id)
as T where T.tweet_id = ${tweetId} group by T.tweet_id;`;
const QueryForLikes = `
select count(like_id) as likes
from (Tweet inner join Like on Tweet.tweet_id = Like.tweet_id)
as T where T.tweet_id = ${tweetId} group by T.tweet_id;`;
const Tweet = await db.get(QueryForTweet);
const Replies = await db.get(QueryForReplies);
const Likes = await db.get(QueryForLikes);
const data = {
tweet: Tweet.tweet,
likes: Likes["likes"],
replies: Replies["replies"],
dateTime: Tweet.date_time,
};
res.json(data);
} else {
res.status(401);
res.send("Invalid Request");
}
});
//api 7
app.get("/tweets/:tweetId/likes/", authenticationFunction, async (req, res) => {
const { tweetId } = req.params;
const requiredTweetQuery = `select * from Tweet where tweet_id = ${tweetId};`;
const requiredTweet = await db.get(requiredTweetQuery);
console.log(requiredTweet);
const { user_id } = requiredTweet;
const username = req.username;
const bringUserId = `
select user_id from User where username like '${username}';`;
let user_id_WhichRequested = await db.get(bringUserId);
user_id_WhichRequested = user_id_WhichRequested.user_id;
console.log(user_id_WhichRequested);
const FollowingsListOfUser = `
select following_user_id from Follower where
follower_user_id = ${user_id_WhichRequested};`;
let followingList = await db.all(FollowingsListOfUser);
console.log(followingList);
let followingList2 = followingList.map((each) => each.following_user_id);
console.log(followingList2);
if (user_id in followingList2) {
const bringLikesQuery = `
select username from User where user_id in
(select user_id from Like where tweet_id = ${tweetId});`;
const allUsername = await db.all(bringLikesQuery);
const allUsernameUpdated = allUsername.map((each) => {
return each.username;
});
res.json({ likes: allUsernameUpdated });
} else {
res.status(401);
res.send("Invalid Request");
}
});
//api 8
app.get(
"/tweets/:tweetId/replies/",
authenticationFunction,
async (req, res) => {
const { tweetId } = req.params;
const username = req.username;
const bringUserId = `
select user_id from User where username like '${username}';`;
let user_id_WhichRequested = await db.get(bringUserId);
user_id_WhichRequested = user_id_WhichRequested.user_id;
//newCode
const getFollowingQuery = `
SELECT distinct(tweet_id) FROM
Follower INNER JOIN Tweet
ON Follower.following_user_id=Tweet.user_id
Where Tweet.tweet_id = ${tweetId} AND Follower.follower_user_id = ${user_id_WhichRequested};`;
const result = await db.get(getFollowingQuery);
if (result === undefined) {
//If there is no results found then the request is invalid
res.status(401);
res.send("Invalid Request");
} else {
const tweetInfoQuery = `
SELECT
name,reply
FROM Reply NATURAL JOIN User
WHERE tweet_id= ${tweetId};`; //Getting the name and replies of the tweet.
const dbResponse = await db.all(tweetInfoQuery);
res.json({ replies: dbResponse }); //Sending response as given in the description.
}
//newCodeEnded
}
);
//api 9
app.get("/user/tweets/", authenticationFunction, async (req, res) => {
const username = req.username;
const bringUserQuery = `
select user_id from User where username = '${username}';`;
const { user_id } = await db.get(bringUserQuery);
const tweetsQuery = `
SELECT
tweet,
(
SELECT COUNT(like_id)
FROM like
WHERE tweet_id=tweet.tweet_id
) AS likes,
(
SELECT COUNT(reply_id)
FROM reply
WHERE tweet_id=tweet.tweet_id
) AS replies,
date_time AS dateTime
FROM tweet
WHERE user_id= ${user_id}
`;
const dataList2 = await db.all(tweetsQuery);
res.json(dataList2);
});
//api 10
app.post("/user/tweets/", authenticationFunction, async (req, res) => {
const { tweet } = req.body;
const username = req.username;
const bringUserQuery = `
select user_id from User where username = '${username}';`;
const { user_id } = await db.get(bringUserQuery);
const createTweetQuery = `
INSERT INTO Tweet ( tweet, user_id)
VALUES( '${tweet}', ${user_id} );`;
await db.run(createTweetQuery);
res.send("Created a Tweet");
});
//api 11
app.delete("/tweets/:tweetId/", authenticationFunction, async (req, res) => {
const { tweetId } = req.params;
console.log(tweetId);
const requiredTweetQuery = `select * from Tweet where tweet_id = ${tweetId};`;
const requiredTweet = await db.get(requiredTweetQuery);
console.log(requiredTweet);
const { user_id } = requiredTweet;
console.log(user_id);
const username = req.username;
const bringUserId = `
select user_id from User where username like '${username}';`;
let user_id_WhichRequested = await db.get(bringUserId);
user_id_WhichRequested = user_id_WhichRequested.user_id;
console.log(user_id_WhichRequested);
if (user_id === user_id_WhichRequested) {
const removeTweetQuery = `
DELETE FROM Tweet
WHERE tweet_id = ${tweetId};`;
await db.run(removeTweetQuery);
res.send("Tweet Removed");
} else {
res.status(401);
res.send("Invalid Request");
}
});
module.exports = app;