Custom Message
In addition to using the built-in message types provided by the SDK, developers can also define custom message types based on their business requirements.
warning
- Custom message types must be registered before sending and receiving such messages.
- It is recommended to consolidate all custom message registration operations between the
initmethod and theconnectmethod for easier management and maintenance. - The message type name and message structure of custom messages must remain consistent across all platforms (including mobile, web, etc.), otherwise message interoperability will fail.
- Do not use "RC:" as a prefix for custom message type names to avoid conflicts with built-in SDK message types.
Registering Custom Messages
Use the RongIMLib.registerMessageType method to register custom message types. The method returns the constructor function corresponding to the message type.
Interface
RongIMLib.registerMessageType(messageType, isPersited, isCounted, searchProps, isStatusMessage)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| messageType | String | Yes | Message type name, must be consistent across platforms |
| isPersited | Boolean | Yes | Whether to store the message |
| isCounted | Boolean | Yes | Whether to count the message |
| searchProps | string[] | Yes | Searchable fields of the message. Not required for web. For numeric fields, the value range is (-2^64, 2^64) and must be an integer |
| isStatusMessage | Boolean | No | Whether it is a status message. Status messages are not stored or counted, and are only received when the recipient is online |
Example Code
const PersonMessage = RongIMLib.registerMessageType('s:person', true, true, [], false)
Sending Custom Messages
Custom messages can be sent using the SDK's sendMessage method.
Example Code
// Construct the custom message to be sent
const message = new PersonMessage({ name: 'someone', age: 18 })
// Send the message
RongIMLib.sendMessage({
conversationType: RongIMLib.ConversationType.PRIVATE,
targetId: '<targetId>'
}, message).then(res => {
if (res.code === 0) {
console.log(res.code, res.data)
} else {
console.log(res.code)
}
})