-
Type: Epic
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
-
To Do
-
Support specifying serialization formatting options at runtime
While the serde helpers cover cases where the schema is known and the user can define a struct to map to it, they aren't sufficient for scenarios where the schema is unknown or the struct is defined in a third party. We should allow serialization configuration options to be specified at runtime to address these scenarios.
e.g. unknown schema converting to JSON with ISO-8601 formatted dates instead of extJSON
let options = bson::extjson::ser::Options::builder().date_format(DateFormat::Iso8601).build(); let json = doc! { "date": Bson::DateTime(Utc::now()) }.into_extjson_with_options(options); // { "date": <ISO 8601 formatted date> }
Another option is to introduce configuration by means of wrapper.
let doc = doc! { "date": Bson::DateTime(Utc::now()) }; let format_options = DocumentFormatOptions::build::date(DateFormat::Iso8601).build(); let wrapped = FormattedDocument::from_doc_with_options(doc, format_options);serde_json::to_value(wrapped).unwrap() // { "date": <ISO 8601 formatted string> }
e.g. dealing with third party struct
// third party struct #[derive(Deserialize)] struct Foo { date: chrono::DateTime<Utc>, } // end third party struct let doc = doc! { "date": Bson::DateTime(Utc::new()) }; let options = bson::de::Options::builder().chrono_date_format(DateFormat::Bson).build(); let foo: Foo = bson::from_document_with_options(doc, options).unwrap(); let ser_options = bson::ser::Options::builder().chrono_date_format(DateFormat::Bson).build(); let doc = bson::to_document(foo).unwrap(); // serializes date as a BSON datetime not a stringĀ
Some of these we could consider enabling by default for ergonomic reasons. E.g. if a user attempts to deserialize a String, but the value at that key in the BSON is a datetime, we could convert the datetime to a String and deserialize that.
- related to
-
RUST-798 DateTime silently loses precision when serialized to BSON
- Closed