Learning Rust By Porting an Express.js Server to Rocket.rs — Part 2

In Part 1 we set up our basic environment and implemented our first very basic route. In this part we are going to establish a connection to our MongoDB server, fetch a user from the database and set up a protected route. Again, this is more of a guideline which you can use to select the exact topics you need to learn in order to write a server in rust, not a fully-fledged tutorial.

Establish a MongoDB connection

Let’s start again by checking out the Express.js version.

let mut client_options = ClientOptions::parse("mongodb://").await?;

Request Guards

Let’s meet Request Guards.

ORM like User structure

So our connection works, and we can continue our journey. Let’s think about our protected route in terms of guards. We want to serve /secret/route only to users of our application. Great so the User itself is our guard! Let’s first implement a User structure.

  • doc! is a macro exported by the MongoDB crate to create BSON objects for our queries. ObjectId::with_string is a helper to create an ObjectID.
  • de::from_document::<User>(user) is a bit of magic. While JSON is such an integral part of (Type|Java)Script, other languages don’t usually come with built in support for this specific type of data structure. For BSON/JSON support we use the Serde crate. With Serde we can serialize and deserialize our rust structs without the need to write any implementations! You might have noticed that we didn’t only derive the Debug trait but also the Deserialize trait. Looking at the documentation for from_document we see that it expects a type which implements the Deserialize trait. The result is a ready to use User struct.

User guard

Finally we want the User struct to be used as a request guard. We can add this functionality by implementing the FromRequest trait.

Putting it all together

This was a lot to unpack so let’s try to create a route which uses our created guard.

Software developer, language enthusiast and Jazz musician.