-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
526 lines (474 loc) · 15 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
const express = require("express");
const app = express();
app.use(express.json());
const { open } = require("sqlite");
const sqlite3 = require("sqlite3");
const path = require("path");
const dbPath = path.join(__dirname, "twitterClone.db");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
let db = null;
const initializeDBAndServer = async () => {
try {
db = await open({
filename: dbPath,
driver: sqlite3.Database,
});
app.listen(3000, () => {
console.log("Server is Running at http://localhost:3000/");
});
} catch (err) {
console.log(`Error : ${err.message}`);
}
};
initializeDBAndServer();
//MIDDLEWARE FUNCTION
//Authentication with JWT Token
//-->JWT Token is Created and called after API-2 login <--
//If the JWT token is not provided by the user or an invalid JWT token is provided
const tokenAuthentication = (request, response, next) => {
let jwtToken;
const authHeader = request.headers["authorization"];
if (authHeader !== undefined) {
jwtToken = authHeader.split(" ")[1];
}
if (jwtToken === undefined) {
response.status(401);
response.send("Invalid JWT Token");
} else {
jwt.verify(jwtToken, "MY_SECRET_TOKEN", async (error, payload) => {
if (error) {
response.status(401);
response.send("Invalid JWT Token");
} else {
//username who logged in passing to all functions in which middleware is called
request.username = payload.username;
next();
}
});
}
};
//API-1
//REGISTER NEW USER
app.post("/register/", async (request, response) => {
const { username, password, name, gender } = request.body;
const hashedPassword = await bcrypt.hash(password, 10);
//SCENARIO-1
//If the username already exists
const checkUserQuery = `
SELECT *
FROM user
WHERE username='${username}';`;
const checkUserResponse = await db.get(checkUserQuery);
if (checkUserResponse !== undefined) {
response.status(400);
response.send("User already exists");
} else {
//SCENARIO-2
//If the registrant provides a password with less than 6 characters
if (password.length < 6) {
response.status(400);
response.send("Password is too short");
} else {
//SCENARIO-3
//Successful login of the user
const createNewUserQuery = `
INSERT INTO user (name, username, password, gender)
VALUES ('${name}', '${username}', '${hashedPassword}', '${gender}');`;
await db.run(createNewUserQuery);
response.status(200);
response.send("User created successfully");
}
}
});
//API-2
//USER LOGIN IF EXISTS IN DB
app.post("/login/", async (request, response) => {
const { username, password } = request.body;
const selectUserQuery = `SELECT * FROM user WHERE username = '${username}'`;
const dbUser = await db.get(selectUserQuery);
if (dbUser === undefined) {
response.status(400);
response.send("Invalid user");
} else {
const isPasswordMatched = await bcrypt.compare(password, dbUser.password);
if (isPasswordMatched === true) {
const payload = {
username: username,
};
const jwtToken = jwt.sign(payload, "MY_SECRET_TOKEN");
response.send({ jwtToken });
} else {
response.status(400);
response.send("Invalid password");
}
}
});
//API-3
// Returns the latest tweets of people whom the user follows. Return 4 tweets at a time
app.get(
"/user/tweets/feed/",
tokenAuthentication,
async (request, response) => {
let { username } = request;
//GETTING USER_ID
const getUserIdQuery = `
SELECT user_id
FROM user
WHERE
username='${username}';`;
const getUserIdResponse = await db.get(getUserIdQuery);
//GET ID'S USER FOLLOWING
const getFollowersQuery = `
SELECT following_user_id
FROM follower
WHERE
follower_user_id=${getUserIdResponse.user_id}`;
const getFollowersResponse = await db.all(getFollowersQuery);
const getFollowerIdsEach = getFollowersResponse.map((eachUser) => {
return eachUser.following_user_id;
});
//GETTING TWEETS WITH LIMIT-4
const getTweetsQuery = `
SELECT user.username, tweet.tweet, tweet.date_time AS dateTime
FROM user INNER JOIN tweet ON user.user_id = tweet.user_id
WHERE user.user_id IN (${getFollowerIdsEach})
ORDER BY
tweet.date_time DESC LIMIT 4 ;`;
const getTweetsResponse = await db.all(getTweetsQuery);
response.send(getTweetsResponse);
}
);
//API-4
//Returns the list of all names of people whom the user follows
app.get("/user/following/", tokenAuthentication, async (request, response) => {
let { username } = request;
//GET USER ID
const getUserIdQuery = `
SELECT user_id
FROM user
WHERE
username='${username}';`;
const getUserIdResponse = await db.get(getUserIdQuery);
//GET USER FOLLOWING ID'S
const getFollowingIds = `
SELECT following_user_id
FROM follower
WHERE follower_user_id=${getUserIdResponse.user_id};`;
const getFollowingIdsResponse = await db.all(getFollowingIds);
const getEachFollowing = getFollowingIdsResponse.map((eachUser) => {
return eachUser.following_user_id;
});
//GET FOLLOWING NAMES
const getFollowingNames = `
SELECT name
FROM user
WHERE user_id IN (${getEachFollowing});`;
const getFollowingNamesResponse = await db.all(getFollowingNames);
response.send(getFollowingNamesResponse);
});
//API-5
//Returns the list of all names of people who follows the user
app.get("/user/followers/", tokenAuthentication, async (request, response) => {
let { username } = request;
//GET USER ID
const getUserIdQuery = `
SELECT user_id
FROM user
WHERE
username='${username}'`;
const getUserIdResponse = await db.get(getUserIdQuery);
//GET FOLLOWER USER ID'S
const getFollowersIds = `
SELECT follower_user_id
FROM follower
WHERE
following_user_id=${getUserIdResponse.user_id};`;
const getFollowersIdsResponse = await db.all(getFollowersIds);
const getFollowerIds = getFollowersIdsResponse.map((eachUser) => {
return eachUser.follower_user_id;
});
const getFollowerNames = `
SELECT name
FROM user
WHERE
user_id IN (${getFollowerIds})`;
const getFollowerNamesResponse = await db.all(getFollowerNames);
response.send(getFollowerNamesResponse);
});
//API-6
//CONVERT TO OBJECT
const convertToObject = (tweets, likesCount, repliesCount) => {
return {
tweet: tweets.tweet,
likes: likesCount.likes,
replies: repliesCount.replies,
dateTime: tweets.date_time,
};
};
//GET TWEETS FOLLOWED BY USER
app.get("/tweets/:tweetId/", tokenAuthentication, async (request, response) => {
const { tweetId } = request.params;
let { username } = request;
//GET USER ID
const getUserIdQuery = `
SELECT user_id
FROM user
WHERE
username='${username}';`;
const getUserIdResponse = await db.get(getUserIdQuery);
//GET ID'S USER FOLLOWING
const getFollowingIds = `
SELECT following_user_id
FROM follower
WHERE follower_user_id=${getUserIdResponse.user_id};`;
const getFollowingIdsResponse = await db.all(getFollowingIds);
const getEachFollowing = getFollowingIdsResponse.map((eachUser) => {
return eachUser.following_user_id;
});
//GET TWEETS FOLLOWED BY USER
const getTweetIdsQuery = `
SELECT tweet_id
FROM tweet
WHERE
user_id in (${getEachFollowing});`;
const getTweetIdsArray = await db.all(getTweetIdsQuery);
const followingUserTweetIds = getTweetIdsArray.map((eachId) => {
return eachId.tweet_id;
});
if (followingUserTweetIds.includes(parseInt(tweetId))) {
const noOfLikesCountQuery = `
SELECT count(user_id) as likes
FROM like
WHERE tweet_id=${tweetId};`;
const noOfLikesCountResponse = await db.get(noOfLikesCountQuery);
const repliesCountQuery = `
SELECT count(user_id) as replies
FROM reply
WHERE tweet_id=${tweetId};`;
const repliesCountResponse = await db.get(repliesCountQuery);
const dataOfTweetQuery = `
SELECT tweet, date_time
FROM tweet
WHERE tweet_id=${tweetId};`;
const dataOfTweetResponse = await db.get(dataOfTweetQuery);
response.send(
convertToObject(
dataOfTweetResponse,
noOfLikesCountResponse,
repliesCountResponse
)
);
} else {
response.status(401);
response.send("Invalid Request");
}
});
//API-7
// CONVERT TO OBJECT
const convertEachLikedNameToObject = (obj) => {
return {
likes: obj,
};
};
//If the user requests a tweet of a user he is following,
// return the list of usernames who liked the tweet
app.get(
"/tweets/:tweetId/likes/",
tokenAuthentication,
async (request, response) => {
const { tweetId } = request.params;
const { username } = request;
//GET USER ID
const getUserIdQuery = `
SELECT user_id
FROM user
WHERE
username='${username}';`;
const getUserIdResponse = await db.get(getUserIdQuery);
//GET USER FOLLOWING ID'S
const userFollowing = `
SELECT following_user_id
FROM follower
WHERE follower_user_id=${getUserIdResponse.user_id};`;
const getFollowingIdsArr = await db.all(userFollowing);
const getFollowingIds = getFollowingIdsArr.map((eachFollower) => {
return eachFollower.following_user_id;
});
//GET TWEET ID AND CHECK MADE BY FOLLOWERS
const getTweetIdsQuery = `
SELECT tweet_id
FROM tweet
WHERE user_id in (${getFollowingIds});`;
const getTweetIdArr = await db.all(getTweetIdsQuery);
const getTweetArr = getTweetIdArr.map((eachTweet) => {
return eachTweet.tweet_id;
});
if (getTweetArr.includes(parseInt(tweetId))) {
const getLikedUsersQuery = `
SELECT user.username AS likes
FROM user INNER JOIN LIKE ON user.user_id = like.user_id
WHERE like.tweet_id=${tweetId};`;
const getLikedUserNames = await db.all(getLikedUsersQuery);
const getLikedUser = getLikedUserNames.map((eachUser) => {
return eachUser.likes;
});
response.send(convertEachLikedNameToObject(getLikedUser));
} else {
response.status(401);
response.send("Invalid Request");
}
}
);
//API-8
//CONVERT OBJECT
const userReplyToObject = (obj) => {
return {
replies: obj,
};
};
//If the user requests a tweet of a user he is following,
// return the list of replies.
app.get(
"/tweets/:tweetId/replies/",
tokenAuthentication,
async (request, response) => {
const { tweetId } = request.params;
let { username } = request;
//GET USER ID
const getUserId = `
SELECT user_id
FROM user
WHERE
username='${username}';`;
const getUserIdResponse = await db.get(getUserId);
//GET USER FOLLOWING ID'S
const getFollowingIdsQuery = `
SELECT following_user_id
FROM follower
WHERE follower_user_id=${getUserIdResponse.user_id};`;
const getFollowingIdsArr = await db.all(getFollowingIdsQuery);
const getFollowingEachIds = getFollowingIdsArr.map((eachId) => {
return eachId.following_user_id;
});
//CHECK TWEET MADE MY PERSON HE IS FOLLOWING
const getTweetIdsQuery = `
SELECT tweet_id
FROM tweet
WHERE user_id in (${getFollowingEachIds})`;
const tweetsIdResponseArr = await db.all(getTweetIdsQuery);
const getTweetId = tweetsIdResponseArr.map((eachTweet) => {
return eachTweet.tweet_id;
});
if (getTweetId.includes(parseInt(tweetId))) {
const getUserReplyTweetsQuery = `
SELECT user.name, reply.reply
FROM user INNER JOIN reply ON user.user_id=reply.user_id
WHERE reply.tweet_id=${tweetId};`;
const getUserReplyResponse = await db.all(getUserReplyTweetsQuery);
response.send(userReplyToObject(getUserReplyResponse));
} else {
response.status(401);
response.send("Invalid Request");
}
}
);
//API-9
//Returns a list of all tweets of the user
app.get("/user/tweets/", tokenAuthentication, async (request, response) => {
let { username } = request;
//GET USER ID
const getUserIdQuery = `
SELECT user_id
FROM user
WHERE username='${username}';`;
const getUserIdResponse = await db.get(getUserIdQuery);
const getTweetsIdOfUser = `
SELECT tweet_id
FROM tweet
WHERE
user_id=${getUserIdResponse.user_id};`;
const getTweetsOfUserResponse = await db.all(getTweetsIdOfUser);
//
const getEachTweetsObj = getTweetsOfUserResponse.map((eachId) => {
return eachId.tweet_id;
});
//GET TWEETS OF THE USER
const getUserTweetsQuery = `
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= ${getUserIdResponse.user_id}`;
const getUserTweetsResponse = await db.all(getUserTweetsQuery);
// console.log(getUserTweetsQuery);
response.send(getUserTweetsResponse);
});
//API-10
//Create a tweet in the tweet table
app.post("/user/tweets/", tokenAuthentication, async (request, response) => {
let { username } = request;
const { tweet } = request.body;
const getUserId = `
SELECT user_id
FROM user
WHERE username='${username}';`;
const getUserIdResponse = await db.get(getUserId);
console.log(getUserIdResponse);
const currentDate = new Date();
const postTweetQuery = `
INSERT INTO tweet(tweet, user_id, date_time)
VALUES ("${tweet}", ${getUserIdResponse.user_id}, '${currentDate}');`;
//POSTING NEW TWEET
const postTweetResponse = await db.run(postTweetQuery);
const tweet_id = postTweetResponse.lastID;
response.send("Created a Tweet");
});
//API-11
//DELETE TWEET POSTED
app.delete(
"/tweets/:tweetId/",
tokenAuthentication,
async (request, response) => {
const { tweetId } = request.params;
const { username } = request;
//get user id
const getUserIdQuery = `
SELECT user_id
FROM user
WHERE username='${username}';`;
const getUserIdResponse = await db.get(getUserIdQuery);
const getUserTweetsQuery = `
SELECT tweet_id
FROM tweet
WHERE user_id=${getUserIdResponse.user_id};`;
const getUserTweetsResponseArr = await db.all(getUserTweetsQuery);
// console.log(getUserTweetsResponseArr);
const getUserTweetsEach = getUserTweetsResponseArr.map((eachTweet) => {
return eachTweet.tweet_id;
});
// console.log(getUserTweetsEach)
if (getUserTweetsEach.includes(parseInt(tweetId))) {
console.log(tweetId);
const deleteUserTweetQuery = `
DELETE FROM tweet
WHERE tweet_id=${tweetId};`;
await db.run(deleteUserTweetQuery);
response.send("Tweet Removed");
} else {
response.status(401);
response.send("Invalid Request");
}
}
);
module.exports = app;