-
Notifications
You must be signed in to change notification settings - Fork 214
/
incoming-mapping.js
58 lines (52 loc) · 2.33 KB
/
incoming-mapping.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Maps the passed parameters to a Ditto Protocol message.
* @param {Object.<string, string>} headers - The headers Object containing all received header values
* @param {string} [textPayload] - The String to be mapped
* @param {ArrayBuffer} [bytePayload] - The bytes to be mapped as ArrayBuffer
* @param {string} [contentType] - The received Content-Type, e.g. "application/json"
* @returns {(DittoProtocolMessage|Array<DittoProtocolMessage>)} dittoProtocolMessage(s) -
* The mapped Ditto Protocol message,
* an array of Ditto Protocol messages or
* <code>null</code> if the message could/should not be mapped
*/
function mapToDittoProtocolMsg(
headers,
textPayload,
bytePayload,
contentType
) {
// ### Insert/adapt your mapping logic here.
// Use helper function Ditto.buildDittoProtocolMsg to build Ditto protocol message
// based on incoming payload.
// See https://www.eclipse.dev/ditto/connectivity-mapping.html#helper-functions for details.
// ### example code assuming the Ditto protocol content type for incoming messages.
if (contentType === 'application/vnd.eclipse.ditto+json') {
// Message is sent as Ditto protocol text payload and can be used directly
return JSON.parse(textPayload);
} else if (contentType === 'application/octet-stream') {
// Message is sent as binary payload; assume Ditto protocol message (JSON).
try {
return JSON.parse(Ditto.arrayBufferToString(bytePayload));
} catch (e) {
// parsing failed (no JSON document); return null to drop the message
return null;
}
}
// no mapping logic matched; return null to drop the message
return null;
}
/**
* Maps the passed external message to a Ditto Protocol message.
* @param {ExternalMessage} externalMsg - The external message to map to a Ditto Protocol message
* @returns {(DittoProtocolMessage|Array<DittoProtocolMessage>)} dittoProtocolMessage(s) -
* The mapped Ditto Protocol message,
* an array of Ditto Protocol messages or
* <code>null</code> if the message could/should not be mapped
*/
function mapToDittoProtocolMsgWrapper(externalMsg) {
let headers = externalMsg.headers;
let textPayload = externalMsg.textPayload;
let bytePayload = externalMsg.bytePayload;
let contentType = externalMsg.contentType;
return mapToDittoProtocolMsg(headers, textPayload, bytePayload, contentType);
}