Skip to content

Commit

Permalink
feat: Respond friend req, refactor: getPendingReq and sendFriendReq api
Browse files Browse the repository at this point in the history
  • Loading branch information
Yash7824 committed May 6, 2024
1 parent 086dd93 commit 1f64406
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 26 deletions.
4 changes: 2 additions & 2 deletions client/src/app/pages/chess-game/chess-game.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@

<div id="player--movements-table" class="w-1/2 self-center xl:self-start lg:self-start md:self-center sm:self-center xl:w-96 lg:w-96 md:w-3/4 sm:w-3/4 m-8">
<div class="flex-1 border-2 border-black">
<span class="text-white text-center align-center justify-center flex">{{ genRule.currentPlayer | titlecase }}'s turn</span>
<span class="text-black text-center align-center justify-center flex">{{ genRule.currentPlayer | titlecase }}'s turn</span>
</div>

<div *ngIf="genRule.IsWhiteKingChecked" class="flex-1 border-2 border-black">
<span class="text-red-600 text-center align-center justify-center flex">{{ genRule.IsWhiteKingChecked }}</span>
</div>

<div class="flex-1 border-2 border-black">
<span class="text-gray-400 text-center align-center justify-center flex">Movements</span>
<span class="text-black text-center align-center justify-center flex">Movements</span>
</div>

<div *ngIf="genRule.IsBlackKingChecked" class="flex-1 border-2 border-black">
Expand Down
6 changes: 5 additions & 1 deletion server/models/FriendRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import mongoose from 'mongoose';
const { Schema } = mongoose;

const FriendRequestSchema = new Schema({
userId: {
currentUserId: {
type: String,
required: true
},
friendId: {
type: String,
required: true
},
user: {
type: String
},
friend: {
type: String
},
Expand Down
5 changes: 1 addition & 4 deletions server/modules/updateMovementList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ import { Socket, Server } from "socket.io";
import { Room } from "../interfaces/room";

const updateMovementList = (io: Server, socket: Socket, updatedMovementList: any, roomName: string, activeRooms: Map<string, Room>, socketIDToUserNameMapper: Map<string,string>) => {
if(activeRooms.get(roomName)!.users.size === 2){
io.to(roomName).emit('updatedMovement', updatedMovementList);
}

io.to(roomName).emit('updatedMovement', updatedMovementList);
}

export default updateMovementList;
115 changes: 96 additions & 19 deletions server/routes/social.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,49 +6,60 @@ import authorization from "../middleware/authorization";
import User from "../models/User";
import FriendRequest from "../models/FriendRequest";
import { FriendRequestDto } from "../dto/FriendRequestDto";
import mongoose from "mongoose";
import { ObjectId } from 'mongodb';

dotenv.config();
const router = express.Router();
const jwtSecret = process.env.jwtSecret;

router.post(
'/searchFriend', async(req: Request, res: Response) => {
try{
'/searchFriend', async (req: Request, res: Response) => {
try {
let friend = req.query.friend
const searchFriend = await User.find({ name: { $regex: new RegExp('^' + friend + '$', 'i') } });
if(!searchFriend) return res.status(400).send('Not Found');
if (!searchFriend) return res.status(400).send('Not Found');
return res.status(200).json(searchFriend);
}catch(error: any){
} catch (error: any) {
return res.status(500).send("Internal Server Error");
}
}
)

router.post('/sendFriendRequest',
[
body('friendId', 'Enter Valid FriendId').isLength({min:1}),
],
[
body('friendId', 'Enter Valid FriendId').isLength({ min: 1 }),
],
authorization,
async(req: any, res: Response) =>{
try{
async (req: any, res: Response) => {
try {

let success = false;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ success, errors: errors.array() });
}
}
const { userId, friendId, friend, status } = req.body;

let currentUser = await User.findById(req.user.id);
if(!currentUser) return res.status(400).send(`Current User doesn't exists`);
if(req.user.id === friendId) return res.status(403).send(`Can't send friend request to self`);

const currentUser = await User.findById(req.user.id);
if (!currentUser) return res.status(404).send(`Current User doesn't exists`);

const friendObject = await User.findById(friendId);
if (!friendObject) return res.status(404).send('Not Found');

const {userId, friendId, friend, status} = req.body;
const friendObject = await User.findOne({id: friendId});
let existingRequest = await FriendRequest.find({ currentUserId: currentUser.id, friendId: friendId });
if (existingRequest.length !== 0) {
if (existingRequest[0].status === 'pending') return res.status(400).send('Friend Request Pending');
return res.status(404).send('Friend Request Already sent')
}

if(!friendObject) return res.status(400).send('Not Found');

let friendRequest = new FriendRequest({
userId: req.user.id,
currentUserId: req.user.id,
friendId: friendId,
user: currentUser.name,
friend: friendObject.name,
status: 'pending'
})

Expand All @@ -61,11 +72,77 @@ router.post('/sendFriendRequest',
date: new Date()
}

await friendRequest.save();
return res.status(200).json(friendRequestDto);
}catch(error: any){
} catch (error: any) {
return res.status(500).send('Internal Server Error: ' + error.message);
}
}
)

router.get('/getPendingFriendRequests',
authorization,
async(req: any, res: Response) => {
try {
let success = false;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ success, errors: errors.array() });
}

const currentUser = await User.findById(req.user.id);
if (!currentUser) return res.status(404).send('Current User not found');

const friendRequest = await FriendRequest.find({ currentUserId: req.user.id })
if (friendRequest.length === 0) return res.status(404).send('No Friend Requests found');

return res.status(200).json(friendRequest);
} catch (error: any) {
return res.status(500).send('Internal Server Error');
}
}
)

router.post('/respondFriendRequest',
[
body('responseToId', 'Enter Valid FriendId').isLength({ min: 1 }),
],
authorization,
async (req: any, res: Response) => {
try {
let success = false;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ success, errors: errors.array() });
}

const { responseToId, action } = req.body;
const currentUser = await User.findOne({ id: req.user.id });
if (!currentUser) return res.status(404).send('Current User not found');

const friendRequest = await FriendRequest.findOne({ friendId: req.user.id, currentUserId: responseToId })
if (!friendRequest) return res.status(404).send('No Friend Requests found');

if (friendRequest.status === 'pending') {
friendRequest.status = action;
}else if(friendRequest.status === 'accept'){
return res.status(400).send('Request already accepted');
}else if(friendRequest.status === 'decline'){
return res.status(403).send('Request was declined');
}else {
return res.status(404).send('Invalid');
}

if(action === 'decline'){
await friendRequest.deleteOne({currentUserId: responseToId});
return res.status(202).send('Friend Request Deleted');
}

await friendRequest.save();
return res.status(200).json(friendRequest);
} catch (error: any) {
return res.status(500).send('Internal Server Error');
}
})

module.exports = router;

0 comments on commit 1f64406

Please sign in to comment.