How do I serialize an object into CBOR format in Motoko?

I’ve added support for @Gekctek CBOR library to the serde library to make it more convenient to convert motoko variables. Here’s an example of how it works:

    import { CBOR } "mo:serde";

    let request : ICRequestContent = { ... content };
    let candid = to_candid(request);
    
    // The encoder requires a list of all the field names in the datatype.
    let fields = ["sender", "canister_id", "method_name", "nonce", "ingress_expiry", "arg"];
    let #ok(cbor) = CBOR.encode(candid, fields, null) else Debug.trap("error converting to cbor");

At the moment, the library doesn’t support variants, but I recently added support for encoding Principals based on the discussion in this forum. However, since the principle is tagged as a blob during this step, it can’t be converted back to the original principle. Instead, it will be converted to Motoko as a Blob. This issue could be solved if there were specific tags for Motoko datatypes that are missing in the CBOR standard for Principals and Variants.

You can convert from CBOR to Motoko using the CBOR.decode() method.