Comments WebSocket Documentation

Overview

The Comments WebSocket API allows real-time interaction with comments on posts. This includes fetching, adding, updating, deleting, and liking comments. The real-time updates are managed through WebSocket events, providing instant feedback to users without refreshing the page.

Note: Ensure that you have a WebSocket client properly connected to the server at https://luminari-a84c1b1dede7.herokuapp.com/ to handle these WebSocket events.

WebSocket Events

getPostComments

Fetch comments for a specific post with pagination support. This event will send a list of comments back to the client, including the total count of comments.

Request Payload:

{
  "postId": "string",
  "page": number (optional, defaults to 1),
  "limit": number (optional, defaults to 10)
}

Response:

{
  "postId": "string",
  "comments": [
    {
      "commentId": "string",
      "postId": "string",
      "text": "string",
      "userId": "string",
      "username": "string",
      "createdAt": "ISODate"
    }
  ],
  "count": number
}

addComment

Add a new comment to a post. This event updates the comment list in real-time for all connected clients.

Request Payload:

{
  "postId": "string",
  "text": "string",
  "userId": "string",
  "username": "string",
  "page": number (optional, defaults to 1),
  "limit": number (optional, defaults to 5)
}

Response:

{
  "postId": "string",
  "comments": [
    {
      "commentId": "string",
      "postId": "string",
      "text": "string",
      "userId": "string",
      "username": "string",
      "createdAt": "ISODate"
    }
  ],
  "count": number
}

deleteComment

Delete a specific comment from a post. The update will be reflected in real-time for all connected clients.

Request Payload:

{
  "postId": "string",
  "commentId": "string",
  "page": number (optional, defaults to 1),
  "limit": number (optional, defaults to 5)
}

Response:

{
  "postId": "string",
  "comments": [
    {
      "commentId": "string",
      "postId": "string",
      "text": "string",
      "userId": "string",
      "username": "string",
      "createdAt": "ISODate"
    }
  ],
  "count": number
}

likeComment

Toggle the like status of a comment. This event updates the like count and status in real-time.

Request Payload:

{
  "commentId": "string",
  "userId": "string"
}

Response:

{
  "commentId": "string",
  "likes": [
    "userId"
  ]
}

Comments WebSocket Example

Overview

This section demonstrates how to use the `useComments` custom hook to interact with comments in a React application. The hook manages fetching, adding, deleting, and liking comments through WebSocket events.

Code Example

The following example shows how to integrate the `useComments` hook into a React component. This hook establishes a WebSocket connection and manages comments for a specific post.

import React, { useState } from 'react';
import useComments from './hooks/useComments';
import { Comment } from './Types/Types';

const PostComments: React.FC<{ postId: string }> = ({ postId }) => {
    const [isOpen, setIsOpen] = useState(true);
    const {
        comments,
        totalComments,
        addComment,
        deleteComment,
        fetchNextPage,
        loading,
        error,
        hasMore,
        likeComment
    } = useComments(postId, isOpen);

    const handleAddComment = async () => {
        await addComment('This is a new comment!', 'userId123', 'username');
    };

    const handleDeleteComment = async (commentId: string) => {
        await deleteComment(commentId);
    };

    const handleLikeComment = (commentId: string) => {
        likeComment(commentId, 'userId123');
    };

    return (
        <div>
            <button onClick={handleAddComment} >Add Comment</button>
            {loading && <p>Loading comments...</p>}
            {error && <p>Error: {error.message}</p>}
            <ul>
                {comments.map((comment: Comment) => (
                    <li key={comment._id} className="mb-4">
                        <p>{comment.username}: {comment.text}</p>
                        <button
                         onClick={() => handleLikeComment(comment._id)} >Like</button>
                        <button
                         onClick={() => handleDeleteComment(comment._id)} >Delete</button>
                    </li>
                ))}
            </ul>
            {hasMore && <button onClick={fetchNextPage}>Load More</button>}
        </div>
    );
};

export default PostComments;

Key Points

  • The `useComments` hook handles all WebSocket interactions for comments, including fetching, adding, deleting, and liking comments.
  • Pagination is managed through the `fetchNextPage` function, which fetches additional comments if available.
  • Real-time updates are received through WebSocket events, ensuring that comment changes are immediately reflected in the UI.

! Note: Notification support for new comments is not available yet and will be added in a future update.