Created
December 20, 2023 17:36
-
-
Save mykhailokrainik/0b4579d1e73e18b37da6b1f59fb848bf to your computer and use it in GitHub Desktop.
&mut Struct to Struct (Rust)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
impl From<(PartialUser, UserEntry, &str)> for AuthorizedUser { | |
fn from((user, entry, jwt_token): (PartialUser, UserEntry, &str)) -> Self { | |
let join_names_fn = | |
|first_name: Option<String>, middle_name: Option<String>, last_name: Option<String>| { | |
let names = [first_name, middle_name, last_name]; | |
names | |
.iter() | |
.filter_map(|name| name.as_ref()) | |
.map(|name| name.to_string()) | |
.collect::<Vec<String>>() | |
.join(" ") | |
}; | |
let permissions = user.permissions_cache.and_then(|permissions| { | |
serde_json::from_slice::<Permissions>(&permissions) | |
.ok() | |
.and_then(|permissions| serde_json::to_string(&permissions).ok()) | |
}); | |
let mut binding = AuthorizedUser { | |
uuid: user.uuid, | |
jwt_token: jwt_token.to_owned(), | |
permissions, | |
..Default::default() | |
}; | |
let auth_user = binding.as_mut(); | |
match entry { | |
UserEntry::Person(person) => { | |
auth_user.email = user.email.or(person.email); | |
auth_user.full_name = join_names_fn( | |
string_to_option(person.first_name), | |
person.middle_name, | |
person.second_name, | |
); | |
}, | |
UserEntry::Client(client) => { | |
auth_user.email = user.email.or(client.email); | |
auth_user.full_name = join_names_fn( | |
string_to_option(client.first_name), | |
client.middle_name, | |
client.second_name, | |
); | |
}, | |
UserEntry::Contractor(contractor) => { | |
auth_user.email = user.email.or(contractor.email); | |
auth_user.full_name = join_names_fn( | |
string_to_option(contractor.first_name), | |
contractor.middle_name, | |
contractor.second_name, | |
); | |
}, | |
} | |
core::mem::take(auth_user) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment