Skip to content

Instantly share code, notes, and snippets.

@BruceL33t
Forked from mhallin/mod.rs
Created September 20, 2017 23:46
Show Gist options
  • Save BruceL33t/97aff037a1b346fbabddba75db93d538 to your computer and use it in GitHub Desktop.
Save BruceL33t/97aff037a1b346fbabddba75db93d538 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