Extracting the user's identifier

To modify a specific user, we need their identifier. REST specifies that you need to get the IDs from a path, because REST maps data entities to URLs.

We can extract a user's identifier using the tail of the path, which we already have. This is  why we use the starts_with method of the string, instead of checking for strong equality with USER_PATH to the path tails.

We previously declared the UserId type, which equals the u64 unsigned number. Add this code to the second branch of the previously-declared match expression with the (method, path) pattern to extract the user's identifier from the path:

let user_id = path.trim_left_matches(USER_PATH)
.parse::<UserId>()
.ok()
.map(|x| x as usize);

The str::trim_left_matches method removes the part of the string if it matches a provided string from the argument. After that, we use the str::parse method, which tries to convert a string (the remaining tail) to a type that implements the FromStr trait of the standard library. UserId already implements this, because it's equal to the u64 type, which can be parsed from the string.

The parse method returns Result. We convert this to an Option instance with Result::ok functions. We won't try to handle errors with the IDs. The None value represents either the absence of a value or a wrong value.

We can also use a map of the returned Option instance to convert a value to the usize type. This is because Slab uses usize for IDs, but the real size of the usize type depends on the platform architecture, which can be different. It can be u32 or u64 depending on the largest memory address that you can use.

Why can't we use usize for UserId since it implements the FromStr trait? This is because a client expects the same behavior as an HTTP server, which doesn't depend on the architecture platform. It's bad practice to use unpredictable size parameters in HTTP requests.

Sometimes, it can be difficult to choose a type to identify the data. We use map to convert the u64 value to usize. This doesn't work, however, for architectures where usize equals u32, because UserId can be larger than the memory limit. It's safe in cases where the microservices are tiny, but this is an important point to bear in mind for microservices that you'll use in production. Often, this problem will be simple to solve, because you can use the ID type of a database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.114.28