Data manipulation functions

Our example needs three functions. The first function, add_session, adds an association between the token and user ID:

fn add_session(conn: &Connection, token: &str, uid: &str) -> Result<(), RedisError> {
conn.hset(SESSIONS, token, uid)
}

This function only calls the hset method of a Connection and sets the uid value by the token key in the SESSIONS map. It returns RedisError if something is wrong with a set operation.

The next function, remove_session, is also pretty simple and calls the hdel method of Connection:

fn remove_session(conn: &Connection, token: &str) -> Result<(), RedisError> {
conn.hdel(SESSIONS, token)
}

This function deletes a record with the token key from the SESSIONS map.

The last function, list_sessions, returns all token-uid pairs as a HashMap instance from the SESSION map. It uses the hgetall method of Connection, which calls the HGETALL method in Redis:

fn list_sessions(conn: &Connection) -> Result<HashMap<String, String>, RedisError> {
conn.hgetall(SESSIONS)
}

As you can see, all functions map to raw Redis commands, which looks pretty simple. But all functions do a good job in the background too, converting values to their corresponding Rust types.

Now, we can create an arguments parser for the session tool.

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

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