Create channel

The next method is create_channel, which creates a new channel for a user. Take a look at the implementation:

pub fn create_channel(&self, user_id: Id, title: &str, is_public: bool)
-> Result<Channel, Error>
{
self.conn.transaction::<_, _, _>(|| {
let channel: Channel = insert_into(channels::table)
.values((
channels::user_id.eq(user_id),
channels::title.eq(title),
channels::is_public.eq(is_public),
))
.returning((
channels::id,
channels::user_id,
channels::title,
channels::is_public,
channels::created_at,
channels::updated_at,
))
.get_result(&self.conn)
.map_err(Error::from)?;
self.add_member(channel.id, user_id)?;
Ok(channel)
})
}

The function expects user_id, the title of a channel, and the is_public flag, which means the channel is public.

Since we have to add the user who created the channel as the first member of a created channel, we will join two statements to a single transaction. To create a transaction with diesel, you can use the transaction method of the Connection instance. This method expects three type parameters—successful value type, error value type, and a type of a closure provided as a single argument with a function call. We skip all types, because the compiler can detect them.

In the transaction implementation we create a Channel model instance that represents a new record in a database. After that, we use the add_member method of our Api struct. As you can see, neither the transaction and connection instances need a mutable reference, and we can combine multiple methods to get an immutable reference to a Connection instance. You will see the implementation of the add_member method later, but now we will add a method to update a channel's record in a table.

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

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