Created
September 20, 2017 15:05
-
-
Save mhallin/c8670327b2f6d1bac69727478d065b8d to your computer and use it in GitHub Desktop.
R2D2, Diesel, Postgres, and Juniper
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
pub struct Ctx { | |
pub db: request::PooledConnection, | |
} | |
impl Context for Ctx {} | |
pub fn context_factory(req: &mut Request) -> Ctx { | |
Ctx { | |
db: request::get_db(req), | |
} | |
} |
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
struct QueryRoot; | |
graphql_object!(QueryRoot: Ctx |&self| { | |
field do_stuff_with_db(&executor) -> FieldResult<i32> { | |
let db = &executor.context().db; | |
db.transaction(|| { | |
// Do stuff... | |
}); | |
Ok(0) | |
} | |
}); |
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
pub type ConnectionManager = r2d2_diesel::ConnectionManager<diesel::pg::PgConnection>; | |
pub type ConnectionPool = r2d2::Pool<ConnectionManager>; | |
pub type PooledConnection = r2d2::PooledConnection<ConnectionManager>; | |
struct DatabaseMarker; | |
impl Key for DatabaseMarker { | |
type Value = ConnectionPool; | |
} | |
pub fn get_db(req: &mut Request) -> PooledConnection { | |
req.get::<Read<DatabaseMarker>>() | |
.expect("Could not get DatabaseMarker from request") | |
.get() | |
.expect("Could not acquire read lock on connection pool") | |
} | |
pub fn prepare_chain(chain: &mut Chain, pool: ConnectionPool) { | |
chain.link(Read::<DatabaseMarker>::both(pool)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment