Skip to content

Implement GET API Endpoint to Retrieve Messages by Channel ID #36

@sahsisunny

Description

@sahsisunny

Title: Implement GET API Endpoint to Retrieve Messages by Channel ID

Description:

We need to implement a GET API endpoint to retrieve all messages for a specific channel in our chat application. The endpoint will accept a channelid as a query parameter and return all messages associated with that channel.

Acceptance Criteria:

  1. Endpoint:

    • URL: /api/messages
    • Method: GET
    • Query Parameter: channelid (required)
  2. Request Parameters:

    • channelid: string (e.g., "general")
  3. Response:

    • On success, return status 200 with an array of messages for the specified channelid.
    • On failure, return appropriate error status and message.
  4. Database:

    • Retrieve messages from the messages table filtered by channelid.
  5. Error Handling:

    • Handle and log any errors, returning an appropriate error response to the client.

Example Request and Response:

Request:

GET /api/messages?channelid=general

Response:

{
    "message": "Messages retrieved successfully",
    "data": [
        {
            "messageid": "unique_message_id_1",
            "channelid": "general",
            "type": "text",
            "content": "Hello, how are you?",
            "sender": {
                "userid": "12345",
                "name": "Alice",
                "avatar": "https://example.com/path/to/avatar.jpg"
            },
            "timestamp": "2024-05-24T10:00:00Z"
        },
        {
            "messageid": "unique_message_id_2",
            "channelid": "general",
            "type": "image",
            "content": "https://example.com/path/to/image.jpg",
            "sender": {
                "userid": "67890",
                "name": "Bob",
                "avatar": "https://example.com/path/to/avatar.jpg"
            },
            "timestamp": "2024-05-24T10:01:00Z"
        },
        {
            "messageid": "unique_message_id_3",
            "channelid": "general",
            "type": "video",
            "content": "https://example.com/path/to/video.mp4",
            "sender": {
                "userid": "54321",
                "name": "Charlie",
                "avatar": "https://example.com/path/to/avatar.jpg"
            },
            "timestamp": "2024-05-24T10:02:00Z"
        }
    ]
}

Technical Notes:

  1. Query Parameters:

    • Validate the presence of channelid.
    • Ensure channelid exists in the database.
  2. Database Schema:

    • Ensure the messages table can be queried efficiently by channelid.
  3. Security:

    • Validate user authentication and authorization.
    • Sanitize input to prevent SQL injection.

Tasks:

  1. Backend:

    • Create the endpoint in the backend framework (e.g., Express.js for Node.js).
    • Validate query parameters.
    • Query the database to retrieve messages by channelid.
    • Return the appropriate response.
  2. Testing:

    • Write unit tests for the API endpoint.
    • Test different scenarios including success and various failure cases.
  3. Documentation:

    • Update API documentation to include the new endpoint.
    • Provide examples of requests and responses.

References:


Example Implementation (Node.js with Express)

Here's a basic example of how you might start implementing the endpoint:

Server Setup (Express.js):

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

app.use(express.json());
app.use(cookieParser());

app.get('/api/messages', async (req, res) => {
    const { channelid } = req.query;

    if (!channelid) {
        return res.status(400).json({ message: 'Channel ID is required' });
    }

    try {
        // Retrieve messages from the database based on channelid
        const messages = await getMessagesByChannelId(channelid);

        res.status(200).json({ message: 'Messages retrieved successfully', data: messages });
    } catch (error) {
        console.error('Error retrieving messages:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
});

// Mock function to simulate database retrieval
const getMessagesByChannelId = async (channelid) => {
    return [
        {
            messageid: 'unique_message_id_1',
            channelid: 'general',
            type: 'text',
            content: 'Hello, how are you?',
            sender: {
                userid: '12345',
                name: 'Alice',
                avatar: 'https://example.com/path/to/avatar.jpg'
            },
            timestamp: '2024-05-24T10:00:00Z'
        },
        {
            messageid: 'unique_message_id_2',
            channelid: 'general',
            type: 'image',
            content: 'https://example.com/path/to/image.jpg',
            sender: {
                userid: '67890',
                name: 'Bob',
                avatar: 'https://example.com/path/to/avatar.jpg'
            },
            timestamp: '2024-05-24T10:01:00Z'
        },
        {
            messageid: 'unique_message_id_3',
            channelid: 'general',
            type: 'video',
            content: 'https://example.com/path/to/video.mp4',
            sender: {
                userid: '54321',
                name: 'Charlie',
                avatar: 'https://example.com/path/to/avatar.jpg'
            },
            timestamp: '2024-05-24T10:02:00Z'
        }
    ];
};

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Notes:

  • Replace the getMessagesByChannelId mock function with actual database logic.
  • Ensure proper error handling and logging.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions