Skip to content

Instantly share code, notes, and snippets.

@trimoq
trimoq / weird_error_handling.rs
Last active March 25, 2020 11:03
Unfinished APIs lead to weird code wrapping around them
bucket
.put_object(&target_path, &bytes, "image/jpg")
.map(|_| ()) // we don't need the result since it is broken anyway
.map_err(|e|
Box::new(NetworkError::UploadPutError(
e.description.unwrap_or("Generic upload error".into()).into())
).into()
)
while let Some(msg) = msg_stream.next().await{
...
}
@trimoq
trimoq / config.rs
Last active March 17, 2020 11:14
excerpt of the config struct
#[derive(StructOpt, Debug, Clone)]
#[structopt(name = "downloader")]
pub struct ConverterConfig{
#[structopt(short = "r", long, default_value = "eu-east2", env = "S3_REGION_NAME")]
pub s3_region_name: String,
}
@trimoq
trimoq / async_process.rs
Last active March 25, 2020 10:02
The slightly simplified process function
pub async fn process(request: DownloadTask, cfg: ConverterConfig) -> Result<...>{
let bytes = download_url(request.url).await?;
let (image, thumbnail) = tokio::task::spawn_blocking(|| process_image(bytes)).await?;
push_to_s3(image, cfg, request.target_path).await?;
push_to_s3(thumbnail, cfg, request.thumbnail_path).await?;
info!("Finished download for {}",request.correlation_id);
trait Generator{
fn generate_UserRepository() -> Box<dyn UserRepository>;
}
@trimoq
trimoq / add_function.rs
Created January 11, 2020 15:48
Using the user_repo without knowing about its type
fn add_user(self, user: User){
// whatever
self.user_repo.add(user);
}
@trimoq
trimoq / UserService.rs
Last active January 11, 2020 15:45
The UserService having a trait object of UserRepository
struct UserService {
user_repo: Box<dyn UserRepository>
}
@trimoq
trimoq / repo.rs
Last active January 8, 2020 14:35
The UserRepository with two imlementations
trait UserRepository{
fn store(&self, user: User);
fn load(&self, id: u32) -> Result<User,Error>;
}
struct PostgresUserRepository;
struct DummyUserRepository;
impl UserRepository for PostgresUserRepository{
...
@trimoq
trimoq / UserService.java
Created January 8, 2020 13:59
UserService having the repository injected
public class UserService{
@Autowired
private UserRepository userRepository;
public void addUser(String name){
// do some business logic here
userRepository.addUser(name);
}
}
@trimoq
trimoq / UserService.java
Last active January 8, 2020 13:57
UserService taking care of its dependencies
public class UserService{
private UserRepository userRepository;
public UserService(){
this.userRepository = PostgresUserRepository.getInstance();
}
public void addUser(String name){
// do some business logic here
userRepository.addUser(name);
}