Skip to content

Implement POST API Endpoint for Sending Messages #35

@sahsisunny

Description

@sahsisunny

Title: Implement POST API Endpoint for Sending Messages

Description:

We need to implement a POST API endpoint to handle the sending of messages within our chat application. The endpoint will accept a payload containing the channelid, type, and content of the message. The senderid should be retrieved from the cookie.

Acceptance Criteria:

  1. Endpoint:

    • URL: /api/messages
    • Method: POST
  2. Request Payload:

    • channelid: string (e.g., "general")
    • type: string (one of "text", "image", "video")
    • content: string (message text or URL for image/video)
  3. Request Processing:

    • Retrieve senderid from the cookie.
    • Validate the presence of channelid, type, and content.
    • Validate that type is one of "text", "image", or "video".
    • Ensure content is properly formatted based on type.
  4. Response:

    • On success, return status 200 with the created message object.
    • On failure, return appropriate error status and message.
  5. Database:

    • Insert the new message into the messages table with channelid, type, content, senderid, and timestamp.
  6. Error Handling:

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

Example Request and Response:

Request:

{
    "channelid": "general",
    "type": "image",
    "content": "https://example.com/path/to/image.jpg"
}

Response:

{
    "message": "Message sent successfully",
    "data": {
        "messageid": "unique_message_id",
        "channelid": "general",
        "type": "image",
        "content": "https://example.com/path/to/image.jpg",
        "sender": {
            "userid": "12345",
            "name": "User Name",
            "avatar": "https://example.com/path/to/avatar.jpg"
        },
        "timestamp": "2024-05-24T12:34:56Z"
    }
}

Technical Notes:

  1. Extracting Sender ID from Cookie:

    • Use a middleware to parse cookies and extract senderid.
  2. Database Schema:

    • Ensure the messages table has columns: messageid, channelid, type, content, senderid, timestamp.
  3. Security:

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

Tasks:

  1. Backend:

    • Create the endpoint in the backend framework (e.g., Express.js for Node.js).
    • Implement cookie parsing middleware.
    • Validate request payload.
    • Interact with the database to store the message.
    • 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 { v4: uuidv4 } = require('uuid');
const app = express();

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

app.post('/api/messages', async (req, res) => {
    const { channelid, type, content } = req.body;
    const senderid = req.cookies.senderid;

    if (!channelid || !type || !content) {
        return res.status(400).json({ message: 'Missing required fields' });
    }

    if (!['text', 'image', 'video'].includes(type)) {
        return res.status(400).json({ message: 'Invalid message type' });
    }

    try {
        const newMessage = {
            messageid: uuidv4(),
            channelid,
            type,
            content,
            sender: {
                userid: senderid,
                name: 'User Name',  // This should be fetched from your user database
                avatar: 'https://example.com/path/to/avatar.jpg'  // This should also come from your user database
            },
            timestamp: new Date().toISOString(),
        };

        // Save newMessage to your database here

        res.status(200).json({ message: 'Message sent successfully', data: newMessage });
    } catch (error) {
        console.error('Error sending message:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
});

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

Notes:

  • This implementation assumes the presence of a senderid cookie.
  • Replace static user details (name, avatar) with actual user data fetched from your database.

Metadata

Metadata

Assignees

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