Skip to main content

context.dispatchWebSocketEvent

The context.dispatchWebSocketEvent function sends WebSocket events to connected clients. This enables real-time push notifications from your mim to browser or app clients.

Enable WebSocket Support

WebSocket events require WEBSOCKET_SUPPORT to be enabled when deploying your mim. See MCM Environment Variables.

Syntax

context.dispatchWebSocketEvent(options)

Parameters

ParameterTypeRequiredDescription
optionsobjectNoEvent configuration object

Options Object

PropertyTypeRequiredDescription
typestringYesThe event type identifier
messagestringNoThe event payload/message

Behavior

  • With options object: Dispatches a WebSocket event with the specified type and optional message
  • Without arguments (or null/undefined): Flushes the event queue

Examples

Basic Event

app.post('/notify', (request, response) => {
context.dispatchWebSocketEvent({
type: 'notification',
message: 'New data available'
});

response.end(JSON.stringify({ sent: true }));
});

Event with JSON Payload

app.post('/user-update', (request, response) => {
var user = JSON.parse(request.body);

// Save user
context.storage.setItemWithTag('user:' + user.id, JSON.stringify(user), 'users');

// Notify connected clients
context.dispatchWebSocketEvent({
type: 'user-updated',
message: JSON.stringify({
userId: user.id,
timestamp: new Date().toISOString()
})
});

response.end(JSON.stringify({ updated: true }));
});

Typed Events

// Define event types as constants
var EVENT_TYPES = {
DATA_SYNC: 'data-sync',
STATUS_CHANGE: 'status-change',
ERROR: 'error'
};

app.post('/sync', (request, response) => {
// Perform sync operation...

context.dispatchWebSocketEvent({
type: EVENT_TYPES.DATA_SYNC,
message: JSON.stringify({
action: 'sync-complete',
recordCount: 42
})
});

response.end(JSON.stringify({ synced: true }));
});

Flush Event Queue

app.post('/flush', (request, response) => {
// Dispatch without arguments to flush the queue
context.dispatchWebSocketEvent();

response.end(JSON.stringify({ flushed: true }));
});

Enabling WebSocket Support

To use dispatchWebSocketEvent, enable WebSocket support when deploying your mim:

curl -X POST http://localhost:8083/mcm/v1/containers \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $EDGE_ACCESS_TOKEN" \
-d '{
"name": "my-mim",
"image": "my-mim-v1",
"env": {
"MCM.BASE_API_PATH": "/my-mim/v1",
"WEBSOCKET_SUPPORT": "true"
}
}'

Client-Side Connection

Clients connect to the WebSocket endpoint to receive events:

// Browser client example
const ws = new WebSocket('ws://localhost:8083/ws/my-mim/v1');

ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Event type:', data.type);
console.log('Message:', data.message);
};

ws.onopen = () => {
console.log('Connected to WebSocket');
};

ws.onclose = () => {
console.log('Disconnected from WebSocket');
};