Implementing subcommands

The implementation of subcommands is simple. For the add subcommand, we extract two arguments, USER_ID and ACTIVITY, and use them to create an Activity struct instance. We also get the current time with the Utc::now method and save it to a datetime field of Activity. Finally, we call the add_activity method to add the Activity instance to the MongoDB database:

match matches.subcommand() {
(CMD_ADD, Some(matches)) => {
let user_id = matches.value_of("USER_ID").unwrap().to_owned();
let activity = matches.value_of("ACTIVITY").unwrap().to_owned();
let activity = Activity {
user_id,
activity,
datetime: Utc::now().to_string(),
};
add_activity(&conn, activity)?;
}
(CMD_LIST, _) => {
let list = list_activities(&conn)?;
for item in list {
println!("User: {:20} Activity: {:20} DateTime: {:20}",
item.user_id, item.activity, item.datetime);
}
}
_ => { matches.usage(); }
}

The list subcommand calls the list_activities function, and then iterates over all records to print them to a Terminal. The logging tool is finished – we can test it now.

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

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