node-red-node-cbor cannot handle BigInt
Which node are you reporting and issue on?
node-red-node-cbor
What are the steps to reproduce?
send a timestamp as integer to decode - the decoder exits with the error message "Bad Decode"
What happens?
the node-red-node-cbor plugin serializes the decoded result with JSON: https://github.com/node-red/node-red-nodes/blob/06a9c48395ab8ba707a0f265162df5c0c81dd74b/parsers/cbor/70-cbor.js#L19
As JSON does not support BigInt, this creates an error message when you are decoding a timestamp for example.
What did you expect to happen?
- The decoder should decode correctly sent buffers without error message.
- The error message should correspond to the actual error.
Proposed solution
- I propose to add a replacer function and convert BigInt and other unsupported formats.
- The error message "not a cbor buffer" is not always correct. I would prefer to use the actual error message.
Additionally, cbor-x library is out of date and should be updated.
Can you provide a simple example flow that shows this ? If I use a simple timestamp it appears to work fine
Are you using second or milliseconds for your timestamp
OK - tried a few "real" bigints and yes - it's just the status that is failing... the actual conversion is fine. Pushed v1.0.2
Thank you for your instant response. I wanted to propose something like that:
// convert types that JSON stringify does not support
function replacer(key, value) {
if (typeof value === 'bigint') {
return value.toString();
}
if (value instanceof Buffer || value instanceof Uint8Array) {
return value.toString('base64');
}
if (value instanceof Map) {
return Array.from(value.entries());
}
if (value instanceof Set) {
return Array.from(value);
}
if (value instanceof RegExp) {
return value.toString();
}
return value;
}
in combination with JSON.stringify(value, replacer) and
catch (e) {
node.error(`Bad decode - ${e.message}`, msg);
}
Looks good - will implement later - or happy to accept a PR if you like.
Great. I'll try a PR (please be patient, I have to learn the process for our organization first)
No problem - shout if you get stuck.