Rocket app with API wrapper used

I'm trying to start using more Rust and I'm having a hard time moving from the Javascript way of thinking to how to do something in Rust.

I'm setting up a server that interacts with an API and returns the processed data to the user. In Javascript, I would create a factory function and set it to a global variable and it would be done. I would be able to use it within route functions on the server and it would hold the same state.

let factory1 = new Factory(); 

function route1(factory) {
    return factory.getApiPoint1(); 
} 

server.get("/api1", route1(factory1)); 

etc. 

However, I'm having a hard time imagining this in Rust. If I have a route like this

// impl and struct for factory object 

#[get("/")]
fn index() -> &'static str {
    // Call factory object here and return result. 
}

how do I pass the factory value into the function? The reason I want to have a singleton is because I want to implement a rate limiting aspect inside of the factory and share it between all calls made to the API. Is there a better way to do this? What is the correct design pattern?

Thank you!

2 Likes

Rocket has managed state for that.

2 Likes

This is perfect. Thank you for giving me a screwdriver as opposed to me using a hammer.

1 Like