Idiomatic way to share reqwest RequestBuilder between multiple functions

hello guys, a beginner here, please i need a way out
i am working on my first project in rust and require the reqwest library
i kinda understand how rust borrowing work a little

this is one function

async fn remove_carousel_files(client: &mut RequestBuilder, carousel_name: String, file_path_name: String) -> bool {
    let command = "removeCarouselFiles";
    let response: Response;
    // let mut client = client.request(Method::GET, BASE_URL);
    let client: RequestBuilder = client.query(&[             // <= cannot move out of `*client` which is behind a mutable reference
        ("command", command), 
        ("fileNamePath1", &file_path_name[..]), 
        ("carouselName", &carousel_name[..])

    response = client.send().await.unwrap() ;
    let response_body: String = response.text().await.unwrap();
    // TODO: No error checking  currently implemented
    // for now we will assume function alway return true
    return true;

if i do this, i get "cannot move out of *client which is behind a mutable reference" which i understand.

one way out is to make the arg client: RequestBuilder. in doing so functions will take ownership
of the object. and will make client object in the calling scope invalid except i return the object back to the calling scope before using it again

earlier version of this function is to make all function create their own RequestBuilder object but then again they do not share any in common except just passing in a common arg and i feel this is more of a waste

It looks like RequestBuilder::send() method will always consume the RequestBuilder, so it's just not possible to reuse it.

An alternative is to create an intermediate struct containing all the information you need when constructing a request, pass that around to populate fields, and give it a to_request() method which does all the RequestBuilder work in one place.

I'm guessing you meant to write "command" and not "commnand"?

Yeah thanks will correct it

Sorry for the late reply, was kind of down a bit.

I did what you suggested and it works well
created a custom PrepareRequestBuilder with function to_request_builder

PrepareRequestBuilder {url: base_url, method: Method::GET, query: &[("sessionId", "")]}

and just pass builder reference to functions


1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.