Interaction functions

Since we have a declared structure, we can add functions to work with databases. The first function we will add is add_activity which adds an activity record to a database:

fn add_activity(conn: &Database, activity: Activity) -> Result<(), Error> {
let doc = doc! {
"user_id": activity.user_id,
"activity": activity.activity,
"datetime": activity.datetime,
};
let coll = conn.collection("activities");
coll.insert_one(doc, None).map(drop)
}

This function only converts the Activity struct into a BSON document, and does this by extracting fields from a struct and construct BSON document with the same fields. We can derive the Serialize trait for the structure and use automatic serialization, but I used the doc! macro for demonstration purposes to show you that you can add a free-form document that can be constructed on the fly.

To add Activity, we get a collection called activities from a Database instance by reference to the collection() method, and call the insert_one method of Collection to add a record.

The next method is list_activities. This method uses a Database instance to find all values in the activities collection. We use the find() method of Collection to get data, but make sure to set filter (the first argument) to None, and options (the second argument) to None, to get all of the values from a collection.

You can tweak these parameters for filtering, or to limit the quantity of records you retrieve:

fn list_activities(conn: &Database) -> Result<Vec<Activity>, Error> {
conn.collection("activities").find(None, None)?
.try_fold(Vec::new(), |mut vec, doc| {
let doc = doc?;
let activity: Activity = bson::from_bson(bson::Bson::Document(doc))?;
vec.push(activity);
Ok(vec)
})
}

To convert every record returned by the find query as a BSON document, we can use the bson::from_bson method, since we have derived the Deserialize trait for the Activity struct. The try_fold method lets us interrupt folding if conversion should fail. We push all successfully converted values to the vector that we provided as the first argument to the try_fold method call. Now, we can parse arguments so that we can prepare a pool to use for calling declared interaction functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.10.45