Created
January 10, 2017 22:19
-
-
Save lholden/a9126184923def301e2b7b436f2f65cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::time::Duration; | |
use postgres::tls::openssl::OpenSsl; | |
use r2d2::{self, PooledConnection}; | |
use r2d2_postgres::{TlsMode, PostgresConnectionManager}; | |
use rocket::Request; | |
use rocket::request::{Outcome, FromRequest}; | |
use rocket::Outcome::{Success, Failure}; | |
use rocket::http::Status; | |
use error::Error; | |
lazy_static! { | |
static ref DB_POOL: r2d2::Pool<PostgresConnectionManager> = { | |
let database_url = env::var("DATABASE_URL").expect("Find DATABASE_URL environment variable"); | |
let config = r2d2::Config::builder() | |
.pool_size(10) | |
.connection_timeout(Duration::from_secs(5)) | |
.build(); | |
let manager = PostgresConnectionManager::new( | |
database_url, | |
TlsMode::Prefer(Box::new(OpenSsl::new().unwrap())) | |
).unwrap(); | |
r2d2::Pool::new(config, manager).expect("Create database pool") | |
}; | |
} | |
pub struct DBConnection(PooledConnection<PostgresConnectionManager>); | |
impl DBConnection { | |
pub fn get(&self) -> &PooledConnection<PostgresConnectionManager> { | |
&self.0 | |
} | |
} | |
impl<'a, 'r> FromRequest<'a, 'r> for DBConnection { | |
type Error = Error; | |
fn from_request(_: &'a Request<'r>) -> Outcome<Self, Self::Error> { | |
match DB_POOL.get() { | |
Ok(conn) => Success(DBConnection(conn)), | |
Err(e) => Failure((Status::InternalServerError, Error::from(e))), | |
} | |
} | |
} | |
/* | |
And then from a controller: | |
#[get("/")] | |
fn bla(conn: DBConnection) -> &'static str { | |
// conn.get().execute(blablabla) | |
... | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment