Crates.io | async-mongodb-session |
lib.rs | async-mongodb-session |
version | 3.0.0 |
source | src |
created_at | 2020-07-31 16:44:27.491232 |
updated_at | 2022-08-21 18:44:49.273824 |
description | An async-session implementation for MongoDB |
homepage | |
repository | https://github.com/yoshuawuyts/async-mongodb-session |
max_upload_size | |
id | 271699 |
size | 39,222 |
$ cargo add async-mongodb-session
This library utilises the document expiration feature in mongodb and is based on specific clock time.
The expiry index is applied to the collection when a new session object is created.
As document expiration is a background task some stale sessions may be present in the database but won't be returned by this library.
Create an HTTP server that keep track of user visits in the session.
#[async_std::main]
async fn main() -> tide::Result<()> {
tide::log::start();
let mut app = tide::new();
app.with(tide::sessions::SessionMiddleware::new(
MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection").await?,
std::env::var("TIDE_SECRET")
.expect(
"Please provide a TIDE_SECRET value of at \
least 32 bytes in order to run this example",
)
.as_bytes(),
));
app.with(tide::utils::Before(
|mut request: tide::Request<()>| async move {
let session = request.session_mut();
let visits: usize = session.get("visits").unwrap_or_default();
session.insert("visits", visits + 1).unwrap();
request
},
));
app.at("/").get(|req: tide::Request<()>| async move {
let visits: usize = req.session().get("visits").unwrap();
Ok(format!("you have visited this website {} times", visits))
});
app.at("/reset")
.get(|mut req: tide::Request<()>| async move {
req.session_mut().destroy();
Ok(tide::Redirect::new("/"))
});
app.listen("127.0.0.1:8080").await?;
Ok(())
}
The tests rely on an running instance of mongodb either on your local machine or remote. The quickest way to get an instance up and running locally is using the following docker command:
$ docker run -d -p 27017:27017 -v ~/data:/data/db mongo:4.2
The tests can then be executed with
$ cargo test
The default settings for the mongodb instance is set to 127.0.0.1:27017 but that can be over ridden by setting the HOST and PORT environment variables.
$ HOST=mymongo.com PORT=1234 cargo test
This crate uses #![deny(unsafe_code)]
to ensure everything is implemented in
100% Safe Rust.
Want to join us? Check out our "Contributing" guide and take a look at some of these issues: