Publish channel

We will add a method that sets the is_public flag of a channel record to true. Look at the following implementation:

pub fn publish_channel(&self, channel_id: Id) -> Result<(), Error> {
let channel = channels::table
.filter(channels::id.eq(channel_id))
.select((
channels::id,
channels::user_id,
channels::title,
channels::is_public,
channels::created_at,
channels::updated_at,
))
.first::<Channel>(&self.conn)
.optional()
.map_err(Error::from)?;
if let Some(channel) = channel {
diesel::update(&channel)
.set(channels::is_public.eq(true))
.execute(&self.conn)?;
Ok(())
} else {
Err(format_err!("channel not found"))
}
}

The function expects channel_id, and we use the table value to create a statement. We use the filter method of the QueryDsl trait to get a single record with the provided ID, and the select method of the same trait to extract values from the table needed for conversion to the Channel model instance. Then, we call the first method that returns the first record found with the executed statement. If no record is found, it will return an error, but since Result types are returned, we can drop the error part of this by converting it in Option with the optional method call. It lets us decide later what to do if a record hasn't been found later.

If a record is found, we use the update method with a reference to a Channel model. This call returns an UpdateStatement value, which has a set method that we use to set the is_public column to true. At the end, we execute this statement for a connection instance. This call also updates the updated_at column of the record automatically since we registered a trigger for the channels table. Now, we can implement the add_member function.

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

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