Skip to content

Instantly share code, notes, and snippets.

@mhallin
Created September 20, 2017 15:05
Show Gist options
  • Save mhallin/c8670327b2f6d1bac69727478d065b8d to your computer and use it in GitHub Desktop.
Save mhallin/c8670327b2f6d1bac69727478d065b8d to your computer and use it in GitHub Desktop.
R2D2, Diesel, Postgres, and Juniper
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),
}
}
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)
}
});
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