Modify data writer APIs on Event (#92)

* Modify setters apis

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>

* Cargo fmt

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>

* Switched into impls in from

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>

* fmt

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>
This commit is contained in:
Francesco Guardiani 2020-10-27 14:10:18 +01:00 committed by GitHub
parent 39af2d7ad0
commit c4305e0713
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 58 additions and 69 deletions

View File

@ -80,6 +80,13 @@ pub trait AttributesWriter {
/// Set the [time](https://github.com/cloudevents/spec/blob/master/spec.md#time).
/// Returns the previous value.
fn set_time(&mut self, time: Option<impl Into<DateTime<Utc>>>) -> Option<DateTime<Utc>>;
/// Set the [datacontenttype](https://github.com/cloudevents/spec/blob/master/spec.md#datacontenttype).
/// Returns the previous value.
fn set_datacontenttype(&mut self, datacontenttype: Option<impl Into<String>>)
-> Option<String>;
/// Set the [dataschema](https://github.com/cloudevents/spec/blob/master/spec.md#dataschema).
/// Returns the previous value.
fn set_dataschema(&mut self, dataschema: Option<impl Into<Url>>) -> Option<Url>;
}
pub(crate) trait AttributesConverter {
@ -87,12 +94,6 @@ pub(crate) trait AttributesConverter {
fn into_v10(self) -> AttributesV10;
}
pub(crate) trait DataAttributesWriter {
fn set_datacontenttype(&mut self, datacontenttype: Option<impl Into<String>>)
-> Option<String>;
fn set_dataschema(&mut self, dataschema: Option<impl Into<Url>>) -> Option<Url>;
}
#[derive(PartialEq, Debug, Clone, Copy)]
pub(crate) enum AttributesIter<'a> {
IterV03(AttributesIntoIteratorV03<'a>),
@ -209,9 +210,7 @@ impl AttributesWriter for Attributes {
Attributes::V10(a) => a.set_time(time),
}
}
}
impl DataAttributesWriter for Attributes {
fn set_datacontenttype(
&mut self,
datacontenttype: Option<impl Into<String>>,

View File

@ -25,8 +25,8 @@ where
/// Create a new empty builder
fn new() -> Self;
/// Build [`super::Event`]
fn build(self) -> Result<super::Event, Error>;
/// Build [`Event`]
fn build(self) -> Result<Event, Error>;
}
/// Represents an error during build process

View File

@ -1,4 +1,5 @@
use serde::export::Formatter;
use serde_json::Value;
use std::convert::{Into, TryFrom};
use std::fmt;
@ -51,21 +52,21 @@ pub(crate) fn is_json_content_type(ct: &str) -> bool {
ct.starts_with("application/json") || ct.starts_with("text/json") || ct.ends_with("+json")
}
impl Into<Data> for serde_json::Value {
fn into(self) -> Data {
Data::Json(self)
impl From<serde_json::Value> for Data {
fn from(value: Value) -> Self {
Data::Json(value)
}
}
impl Into<Data> for Vec<u8> {
fn into(self) -> Data {
Data::Binary(self)
impl From<Vec<u8>> for Data {
fn from(value: Vec<u8>) -> Self {
Data::Binary(value)
}
}
impl Into<Data> for String {
fn into(self) -> Data {
Data::String(self)
impl From<String> for Data {
fn from(value: String) -> Self {
Data::String(value)
}
}

View File

@ -2,7 +2,6 @@ use super::{
AttributeValue, Attributes, AttributesReader, AttributesV10, AttributesWriter, Data,
ExtensionValue, SpecVersion,
};
use crate::event::attributes::DataAttributesWriter;
use chrono::{DateTime, Utc};
use delegate_attr::delegate;
use std::collections::HashMap;
@ -22,7 +21,7 @@ use url::Url;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// // Create an event using the Default trait
/// let mut e = Event::default();
/// e.write_data(
/// e.set_data(
/// "application/json",
/// serde_json::json!({"hello": "world"})
/// );
@ -65,6 +64,9 @@ impl AttributesWriter for Event {
fn set_type(&mut self, ty: impl Into<String>) -> String;
fn set_subject(&mut self, subject: Option<impl Into<String>>) -> Option<String>;
fn set_time(&mut self, time: Option<impl Into<DateTime<Utc>>>) -> Option<DateTime<Utc>>;
fn set_datacontenttype(&mut self, datacontenttype: Option<impl Into<String>>)
-> Option<String>;
fn set_dataschema(&mut self, dataschema: Option<impl Into<Url>>) -> Option<Url>;
}
impl Default for Event {
@ -96,6 +98,11 @@ impl Event {
self.extensions.iter().map(|(k, v)| (k.as_str(), v))
}
/// Get `data` from this `Event`
pub fn data(&self) -> Option<&Data> {
self.data.as_ref()
}
/// Take (`datacontenttype`, `dataschema`, `data`) from this event, leaving these fields empty
///
/// ```
@ -104,7 +111,7 @@ impl Event {
/// use std::convert::Into;
///
/// let mut e = Event::default();
/// e.write_data("application/json", json!({}));
/// e.set_data("application/json", json!({}));
///
/// let (datacontenttype, dataschema, data) = e.take_data();
/// ```
@ -116,7 +123,8 @@ impl Event {
)
}
/// Write `data` into this `Event` with the specified `datacontenttype`.
/// Set `data` into this `Event` with the specified `datacontenttype`.
/// Returns the previous value of `datacontenttype` and `data`.
///
/// ```
/// use cloudevents::Event;
@ -124,43 +132,32 @@ impl Event {
/// use std::convert::Into;
///
/// let mut e = Event::default();
/// e.write_data("application/json", json!({}))
/// let (old_datacontenttype, old_data) = e.set_data("application/json", json!({}));
/// ```
pub fn write_data(&mut self, datacontenttype: impl Into<String>, data: impl Into<Data>) {
self.attributes.set_datacontenttype(Some(datacontenttype));
self.attributes.set_dataschema(None as Option<Url>);
self.data = Some(data.into());
}
/// Get `data` from this `Event`
pub fn data(&self) -> Option<&Data> {
self.data.as_ref()
}
/// Write `data` into this `Event` with the specified `datacontenttype` and `dataschema`.
///
/// ```
/// use cloudevents::Event;
/// use serde_json::json;
/// use std::convert::Into;
/// use url::Url;
///
/// let mut e = Event::default();
/// e.write_data_with_schema(
/// "application/json",
/// Url::parse("http://myapplication.com/schema").unwrap(),
/// json!({})
/// )
/// ```
pub fn write_data_with_schema(
pub fn set_data(
&mut self,
datacontenttype: impl Into<String>,
dataschema: impl Into<Url>,
data: impl Into<Data>,
) {
self.attributes.set_datacontenttype(Some(datacontenttype));
self.attributes.set_dataschema(Some(dataschema));
self.data = Some(data.into());
) -> (Option<String>, Option<Data>) {
(
self.attributes.set_datacontenttype(Some(datacontenttype)),
std::mem::replace(&mut self.data, Some(data.into())),
)
}
/// Set `data` into this `Event`, without checking if there is a `datacontenttype`.
/// Returns the previous value of `data`.
///
/// ```
/// use cloudevents::Event;
/// use serde_json::json;
/// use std::convert::Into;
///
/// let mut e = Event::default();
/// let old_data = e.set_data_unchecked(json!({}));
/// ```
pub fn set_data_unchecked(&mut self, data: impl Into<Data>) -> Option<Data> {
std::mem::replace(&mut self.data, Some(data.into()))
}
/// Get the [extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) named `extension_name`
@ -194,7 +191,7 @@ mod tests {
#[test]
fn take_data() {
let mut e = Event::default();
e.write_data(
e.set_data(
"application/json",
serde_json::json!({
"hello": "world"
@ -225,7 +222,7 @@ mod tests {
fn iter() {
let mut e = Event::default();
e.set_extension("aaa", "bbb");
e.write_data(
e.set_data(
"application/json",
serde_json::json!({
"hello": "world"

View File

@ -24,6 +24,7 @@ impl TryIntoUrl for String {
}
}
/// Trait to define conversion to [`DateTime`]
pub trait TryIntoTime {
fn into_time(self) -> Result<DateTime<Utc>, chrono::ParseError>;
}
@ -34,7 +35,6 @@ impl TryIntoTime for DateTime<Utc> {
}
}
/// Trait to define conversion to [`DateTime`]
impl TryIntoTime for &str {
fn into_time(self) -> Result<DateTime<Utc>, chrono::ParseError> {
Ok(DateTime::<Utc>::from(DateTime::parse_from_rfc3339(self)?))

View File

@ -1,6 +1,4 @@
use crate::event::attributes::{
default_hostname, AttributeValue, AttributesConverter, DataAttributesWriter,
};
use crate::event::attributes::{default_hostname, AttributeValue, AttributesConverter};
use crate::event::AttributesV10;
use crate::event::{AttributesReader, AttributesWriter, SpecVersion};
use crate::message::{BinarySerializer, MessageAttributeValue};
@ -141,9 +139,7 @@ impl AttributesWriter for Attributes {
fn set_time(&mut self, time: Option<impl Into<DateTime<Utc>>>) -> Option<DateTime<Utc>> {
std::mem::replace(&mut self.time, time.map(Into::into))
}
}
impl DataAttributesWriter for Attributes {
fn set_datacontenttype(
&mut self,
datacontenttype: Option<impl Into<String>>,

View File

@ -1,6 +1,4 @@
use crate::event::attributes::{
default_hostname, AttributeValue, AttributesConverter, DataAttributesWriter,
};
use crate::event::attributes::{default_hostname, AttributeValue, AttributesConverter};
use crate::event::{AttributesReader, AttributesV03, AttributesWriter, SpecVersion};
use crate::message::{BinarySerializer, MessageAttributeValue};
use chrono::{DateTime, Utc};
@ -141,9 +139,7 @@ impl AttributesWriter for Attributes {
fn set_time(&mut self, time: Option<impl Into<DateTime<Utc>>>) -> Option<DateTime<Utc>> {
std::mem::replace(&mut self.time, time.map(Into::into))
}
}
impl DataAttributesWriter for Attributes {
fn set_datacontenttype(
&mut self,
datacontenttype: Option<impl Into<String>>,