Feature: Sending Messages
Relevant source files
The following files were used as context for generating this wiki page:The "Sending Messages" feature is the core functionality of MessageJS. It provides a unified mechanism for developers to send messages through various platforms like WhatsApp, Telegram, and SMS from their applications. The system is designed to be secure, abstracting away provider credentials from the client-side application and handling the communication through a dedicated backend API.
The overall architecture follows a simple flow: a request is initiated from the client-side SDK, authenticated and processed by the core backend API, which then routes the message to the appropriate third-party messaging service. This process is designed to be asynchronous, with the API immediately acknowledging the request and queuing the message for delivery.
Sources: README.md, QUICK_START.md
Architecture Overview
The message sending process involves two primary packages: @messagejs/client (the frontend SDK) and @messagejs/core (the backend API). The client SDK makes a secure request to the API, which then handles the logic of communicating with the external messaging provider.
This diagram illustrates the high-level data flow for sending a message.
Client-Side Integration (@messagejs/client)
The @messagejs/client package provides a lightweight SDK for browsers and Node.js environments. It exposes a simple API to initialize the service and send messages.
MessageJS Class
The SDK exports a singleton instance of the MessageJS class, which manages the API key and communication with the backend.
Sources: packages/client/src/index.ts:70-132
Initialization
Before sending a message, the SDK must be initialized with a project-specific API key. The base URL for the API can also be optionally configured for self-hosted instances.
import messagejs from 'messagejs-client';
// Initialize with your API key and project ID
messagejs.init(
'sk_live_abc123def456...', // Your API key
'proj_xyz789', // Your project ID
{
endpoint: 'https://api.messagejs.pro', // optional
}
);
Sources: QUICK_START.md, packages/client/src/index.ts:89-99
Sending a Message
The sendMessage method sends the request to the backend API. It takes a SendParams object containing the recipient, template, and connector information.
SendParams Interface
These are the parameters required by the sendMessage method.
| Parameter | Type | Description |
|---|---|---|
connectorId | string | The ID of the connector configuration to use. |
templateId | string | The ID of the message template to use. |
to | string | The recipient's identifier (e.g., E.164 phone number). |
variables | Record<string, any> | Key-value pairs to replace variables in the template. |
metadata | Record<string, any> | Optional metadata for logging and tracking. |
Sources: packages/client/src/index.ts:39-60
Example Usage
async function sendWelcomeMessage() {
const result = await messagejs.sendMessage({
to: '+1234567890',
message: 'Hello from MessageJS!', // Note: QUICK_START.md shows `message`, but SDK types show `templateId`
connector: 'whatsapp' // Note: QUICK_START.md shows `connector`, but SDK types show `connectorId`
});
if (result.success) {
console.log('Message sent!', result.messageId);
} else {
console.error('Error:', result.error);
}
}
Sources: QUICK_START.md, packages/client/src/index.ts:106-132
Server-Side API (@messagejs/core)
The backend is an Express.js application that exposes a REST API to handle message requests.
API Endpoint: POST /api/v1/messages
This is the primary endpoint for accepting new messages. It is protected and requires a valid API key.
| Property | Description |
|---|---|
| Method | POST |
| Path | /api/v1/messages |
| Authentication | Bearer <api_key> in Authorization header. |
| Success Response | 202 Accepted |
| Error Responses | 400, 401, 403, 500 |
Sources: packages/core/src/api/routes/messageRoutes.ts:16-21, API_REFERENCE.md
Authentication
Every request to the POST /api/v1/messages endpoint is first processed by the validateApiKey middleware. This middleware checks for a valid Bearer token in the Authorization header. If the key is valid, it attaches API key details (like projectId) to the Express request object for use in the controller.
Sources: packages/core/src/api/middleware/authMiddleware.ts:14-74, packages/core/src/api/routes/messageRoutes.ts:19
Request and Response Payloads
The API has clearly defined data structures for requests and responses.
SendMessageRequest Body
This interface defines the expected JSON body for the POST /api/v1/messages request.
| Field | Type | Description |
|---|---|---|
connectorId | string | ID of the connector to use. |
templateId | string | ID of the template to use. |
to | string | Recipient's identifier. |
variables | Record<string, any> | Values for template placeholders. |
metadata | Record<string, any> | Optional user-provided metadata. |
Sources: packages/core/src/types/apiTypes.ts:41-48
SendMessageSuccessResponse
On successful validation and queuing, the API returns a 202 Accepted status with the following body, confirming the message has been accepted for processing.
| Field | Type | Description |
|---|---|---|
messageId | string | A unique ID for the created message log. |
status | "queued" | The initial status of the message. |
externalId | string | null | The ID from the third-party provider (null at this stage). |
details | string | A human-readable message, e.g., "Message has been accepted for processing." |
Sources: packages/core/src/types/apiTypes.ts:53-59, packages/core/src/api/controllers/messageController.ts:60-65
Controller Logic
The sendMessage controller in messageController.ts contains the core logic. The current implementation is a mock that simulates a successful queuing. The planned logic includes:
- Input validation of the request body.
- Fetching
ConnectorandTemplateentities from the database. - Verifying that the entities belong to the project associated with the API key.
- Creating a
MessageLogentry in the database with aqueuedstatus. - Pushing a job to a message queue for asynchronous processing.
Sources: packages/core/src/api/controllers/messageController.ts:22-54
Database Model (MessageLog)
When a message request is accepted, a MessageLog record is created in the database to track its lifecycle.
This ER diagram shows the MessageLog model and its relationships to other entities.
End-to-End Sequence Flow
This diagram shows the complete sequence of events from the client SDK call to the API response.
Summary
The message sending feature is a well-defined system that separates client-side concerns from secure backend operations. It uses a client SDK to communicate with a protected API endpoint, which validates the request and queues it for asynchronous delivery. The entire process is tracked via a MessageLog in the database, providing a robust foundation for a reliable messaging service.