Payloads (base64 vs rawJson)
Centrifugo payloads are bytes. To cross the Tauri bridge as strings, the plugin uses base64 by default and accepts raw JSON as an option.
Sending
publish, rpc and send take data as a string plus an optional dataEncoding:
dataEncoding | data must be | Sent to the server |
|---|---|---|
'base64' (default) | base64 | the decoded bytes |
'rawJson' | valid JSON text | the text as is |
Invalid base64 rejects with Base64Error, invalid JSON with SerializationError, before
anything is sent. With the JSON protocol (useProtobuf: false) the server expects JSON data, so
send JSON either way; with Protobuf any bytes work.
import { publish, helpers, utils } from "tauri-plugin-centrifugo-api";
await publish({ channel: "a", data: utils.encodeJson({ x: 1 }) }); // base64
await publish({ channel: "a", data: JSON.stringify({ x: 1 }), dataEncoding: "rawJson" });
await helpers.publishJson("a", { x: 1 }); // same as the first line
await helpers.publishRawJson("a", { x: 1 }); // same as the second line
Receiving
publication, server_publication and history() items always carry data in base64
(dataEncoding: 'base64') and, when the bytes are valid JSON, also rawJson with the parsed
value. rpc() resolves to base64.
await onPublication(({ payload }) => {
const value = payload.rawJson ?? utils.decode(payload.data);
});
onMessage and the other decoded message helpers do
this for you.
utils
| Function | Does |
|---|---|
utils.encode(text) / utils.decode(b64) | btoa / atob |
utils.encodeJson(value) / utils.decodeJson(b64) | JSON.stringify + btoa / atob + JSON.parse |
btoa/atob work on Latin-1 strings only. For text with other characters encode it as UTF-8
first, or use rawJson:
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode("привет")));
await publish({ channel: "a", data: b64 });
await helpers.publishRawJson("a", { text: "привет" }); // no base64 step at all