summaryrefslogtreecommitdiff
path: root/server/src
diff options
context:
space:
mode:
Diffstat (limited to 'server/src')
-rw-r--r--server/src/db.rs20
-rw-r--r--server/src/errors.rs11
-rw-r--r--server/src/main.rs8
3 files changed, 39 insertions, 0 deletions
diff --git a/server/src/db.rs b/server/src/db.rs
new file mode 100644
index 0000000..8cc4d1f
--- /dev/null
+++ b/server/src/db.rs
@@ -0,0 +1,20 @@
+use crate::errors::AppError;
+
+use sqlx::postgres::PgPool;
+
+static mut CONNECTION: Option<PgPool> = None;
+
+pub async fn setup() -> Result<(), AppError> {
+ let database_url =
+ std::env::var("DATABASE_URL").expect("Define `DATABASE_URL` environment variable.");
+
+ unsafe {
+ CONNECTION = Some(PgPool::connect(&database_url).await?);
+ }
+
+ Ok(())
+}
+
+pub unsafe fn get_client() -> Option<&'static PgPool> {
+ CONNECTION.as_ref()
+}
diff --git a/server/src/errors.rs b/server/src/errors.rs
index cf59d0c..dc0468e 100644
--- a/server/src/errors.rs
+++ b/server/src/errors.rs
@@ -7,6 +7,7 @@ use serde_json::json;
pub enum AppError {
Generic,
+ Database,
}
impl IntoResponse for AppError {
@@ -16,6 +17,10 @@ impl IntoResponse for AppError {
StatusCode::INTERNAL_SERVER_ERROR,
"Generic error, can't find why",
),
+ AppError::Database => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "Error with database connection",
+ ),
};
let body = Json(json!({
@@ -25,3 +30,9 @@ impl IntoResponse for AppError {
(status, body).into_response()
}
}
+
+impl From<sqlx::Error> for AppError {
+ fn from(_error: sqlx::Error) -> AppError {
+ AppError::Database
+ }
+}
diff --git a/server/src/main.rs b/server/src/main.rs
index 2f4a727..e061b83 100644
--- a/server/src/main.rs
+++ b/server/src/main.rs
@@ -1,6 +1,7 @@
mod db;
mod errors;
mod logger;
+use sqlx::postgres::PgPool;
use axum::{
http::{header, Request},
@@ -29,6 +30,13 @@ async fn main() {
async fn create_app() -> Router {
logger::setup();
+ let _ = db::setup().await;
+ let pool = unsafe {
+ match db::get_client() {
+ Some(client) => client,
+ None => panic!("Connection not established!"),
+ }
+ };
Router::new()
.route("/", get(hej))