We will declare a struct with a connection instance inside and add methods over this connection:
pub struct Api {
conn: PgConnection,
}
The Api struct can be created with the connect method, which uses the DATABASE_URL environment variable to bootstrap a connection to PostgreSQL:
impl Api {
pub fn connect() -> Result<Self, Error> {
let database_url = env::var("DATABASE_URL")
.unwrap_or("postgres://postgres@localhost:5432".to_string());
let conn = PgConnection::establish(&database_url)?;
Ok(Self { conn })
}
}
We use a direct connection here without an r2d2 pool, but you can also make the Api struct compatible with concurrent access. Let's add first the API method for registering new users.