Skip to content

Commit

Permalink
community questions socket, sort by newest
Browse files Browse the repository at this point in the history
  • Loading branch information
g-pooja-03 committed Nov 27, 2024
1 parent fae1843 commit 7c06ce8
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import React, { useEffect, useState } from 'react';
import { getCommunityQuestions } from '../../../../../services/communityService';
import { Question } from '../../../../../types';
Expand All @@ -11,26 +12,39 @@ import useUserContext from '../../../../../hooks/useUserContext';
const CommunityQuestions = () => {
const [questions, setQuestions] = useState<Question[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const { user } = useUserContext();
const { user, socket } = useUserContext();

useEffect(() => {
const fetchQuestions = async () => {
try {
const fetchedQuestions = await getCommunityQuestions(user.community);
// console.log(fetchedQuestions);
setQuestions(fetchedQuestions);
if (user.community) {
const fetchedQuestions = await getCommunityQuestions(user.community);
setQuestions(fetchedQuestions);
}
} catch (err) {
// eslint-disable-next-line no-console
console.error('Failed to fetch questions');
} finally {
setLoading(false);
}
};

if (user.community) {
fetchQuestions();
}
}, [user.community]);
fetchQuestions();

const handleCommunityQuestionUpdate = (community: { name: string; questions: Question[] }) => {
if (community.name === user.community) {
console.log(community.name);
console.log(community.questions);
console.log(`Received question update for community: ${community.name}`);
setQuestions(community.questions);
}
};

socket.on('communityQuestionUpdate', handleCommunityQuestionUpdate);

return () => {
socket.off('communityQuestionUpdate', handleCommunityQuestionUpdate);
};
}, [user.community, socket]);

if (loading) return <p>Loading questions...</p>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const MembersSidebar = () => {

socket.on('communityUpdate', handleCommunityUpdate);
return () => {
socket.off('communityUpdate');
socket.off('communityUpdate', handleCommunityUpdate);
};
}, [user.community, socket]);

Expand Down
8 changes: 8 additions & 0 deletions client/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,13 @@ export interface CommunityUpdatePayload {
questions: Question[];
}

export interface CommunityQuestionUpdatePayload {
name: string;
tags: string[];
users: string[];
questions: Question[];
}

export interface CommunityData {
name: string;
tags: string[];
Expand All @@ -175,6 +182,7 @@ export interface ServerToClientEvents {
voteUpdate: (vote: VoteUpdatePayload) => void;
commentUpdate: (update: CommentUpdatePayload) => void;
communityUpdate: (update: CommunityUpdatePayload) => void;
communityQuestionUpdate: (update: CommunityQuestionUpdatePayload) => void;
editQuestionUpdate: (update: EditQuestionPayload) => void;
}

Expand Down
27 changes: 21 additions & 6 deletions server/controller/community.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/* eslint-disable no-console */
import express, { Request, Response, Router } from 'express';
import CommunityModel from '../models/communities';
import { Community, FakeSOSocket } from '../types';
import { Community, FakeSOSocket, Question } from '../types';
import TagModel from '../models/tags';
import QuestionModel from '../models/questions';
import { sortQuestionsByNewest } from '../models/application';

const communityController = (socket: FakeSOSocket) => {
const router: Router = express.Router();
Expand Down Expand Up @@ -52,7 +53,7 @@ const communityController = (socket: FakeSOSocket) => {
return;
}

res.json(communityData.questions);
res.json(sortQuestionsByNewest(communityData.questions as Question[]));
} catch (error) {
res.status(500).json({ error: 'Error retrieving questions for the community' });
}
Expand All @@ -77,7 +78,6 @@ const communityController = (socket: FakeSOSocket) => {
socket.emit('communityUpdate', {
name: comm.name,
users: comm.users.filter(user => user !== username),
tags: comm.tags,
});
});
res.status(200).json({ message: 'User removed from all communities successfully' });
Expand All @@ -91,7 +91,6 @@ const communityController = (socket: FakeSOSocket) => {
socket.emit('communityUpdate', {
name: comm.name,
users: comm.users.filter(user => user !== username),
tags: comm.tags,
});
});

Expand All @@ -107,7 +106,6 @@ const communityController = (socket: FakeSOSocket) => {
}
socket.emit('communityUpdate', {
name: newCommunity.name,
tags: newCommunity.tags,
users: newCommunity.users,
});
console.log(`Added user: ${username} to new community: ${newCommunity}`);
Expand Down Expand Up @@ -162,10 +160,27 @@ const communityController = (socket: FakeSOSocket) => {

const updatedCommunity = await CommunityModel.findOneAndUpdate(
{ name: communityName },
{ $addToSet: { questions: questionId } },
{ $addToSet: { questions: existingQuestion as Question } },
{ new: true, runValidators: true },
);

const populatedCommunity = await CommunityModel.findOne({ name: communityName }).populate({
path: 'questions',
populate: [
{ path: 'tags', model: 'Tag' },
{ path: 'answers', model: 'Answer' },
],
});

// console.log(populatedCommunity);
if (populatedCommunity) {
console.log(populatedCommunity.questions);
socket.emit('communityQuestionUpdate', {
name: communityName,
questions: populatedCommunity.questions as Question[],
});
}

if (!updatedCommunity) {
res.status(404).json({ error: 'Community not found.' });
return;
Expand Down
2 changes: 2 additions & 0 deletions server/controller/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,14 @@ const userController = (socket: FakeSOSocket) => {

if (!username) {
res.status(400).json({ error: 'Username is required' });
return;
}

const user = await UserModel.findOne({ username });

if (!user) {
res.status(404).json({ error: 'User not found' });
return;
}

res.status(200).json(user);
Expand Down
2 changes: 1 addition & 1 deletion server/models/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const checkKeywordInQuestion = (q: Question, keywordlist: string[]): boolean =>
*
* @returns {Question[]} - The sorted list of questions
*/
const sortQuestionsByNewest = (qlist: Question[]): Question[] =>
export const sortQuestionsByNewest = (qlist: Question[]): Question[] =>
qlist.sort((a, b) => {
if (a.askDateTime > b.askDateTime) {
return -1;
Expand Down
7 changes: 6 additions & 1 deletion server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,14 @@ export interface AnswerUpdatePayload {

export interface CommunityUpdatePayload {
name: string;
tags: string[];
users: string[];
}

export interface CommunityQuestionUpdatePayload {
name: string;
questions: Question[];
}

// ADD COMMENT
export interface communityRequest extends Request {
body: {
Expand Down Expand Up @@ -261,5 +265,6 @@ export interface ServerToClientEvents {
voteUpdate: (vote: VoteUpdatePayload) => void;
commentUpdate: (comment: CommentUpdatePayload) => void;
communityUpdate: (community: CommunityUpdatePayload) => void;
communityQuestionUpdate: (community: CommunityQuestionUpdatePayload) => void;
editQuestionUpdate: (update: EditQuestionPayload) => void;
}

0 comments on commit 7c06ce8

Please sign in to comment.