Skip to content

Instantly share code, notes, and snippets.

@tadghh
Created November 30, 2024 19:51
Show Gist options
  • Save tadghh/84a36fc94c5547a859c1829593f30867 to your computer and use it in GitHub Desktop.
Save tadghh/84a36fc94c5547a859c1829593f30867 to your computer and use it in GitHub Desktop.
use core::fmt;
use std::{env::VarError, io};
use leptos::ServerFnError;
use sqlx::{postgres::PgPoolOptions, PgPool};
use tokio::sync::OnceCell;
use super::{
blog::{BlogError, BlogPreview},
project::ProjectPreview,
};
static DB: OnceCell<PgPool> = OnceCell::const_new();
#[derive(Debug)]
pub enum DBBlogError {
DatabaseError(String),
EnvVarError(String),
Other(String),
}
impl fmt::Display for DBBlogError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DBBlogError::DatabaseError(msg) => write!(f, "Database error: {}", msg),
DBBlogError::EnvVarError(msg) => write!(f, "Environment variable error: {}", msg),
DBBlogError::Other(msg) => write!(f, "Error: {}", msg),
}
}
}
impl From<sqlx::Error> for BlogError {
fn from(error: sqlx::Error) -> Self {
BlogError::Database(error)
}
}
impl From<sqlx::Error> for DBBlogError {
fn from(err: sqlx::Error) -> Self {
DBBlogError::DatabaseError(err.to_string())
}
}
impl From<BlogError> for ServerFnError {
fn from(error: BlogError) -> Self {
ServerFnError::ServerError(error.to_string())
}
}
impl From<DBBlogError> for io::Error {
fn from(err: DBBlogError) -> io::Error {
io::Error::new(io::ErrorKind::Other, err.to_string())
}
}
impl From<VarError> for DBBlogError {
fn from(err: VarError) -> Self {
DBBlogError::EnvVarError(err.to_string())
}
}
async fn create_pool() -> Result<PgPool, DBBlogError> {
let database_url = std::env::var("DATABASE_URL")?;
let pool = PgPoolOptions::new()
.max_connections(2)
.connect(&database_url)
.await?;
Ok(pool)
}
pub async fn init_db() -> Result<(), DBBlogError> {
let pool = create_pool().await?;
DB.set(pool)
.map_err(|e| DBBlogError::Other(e.to_string()))?;
Ok(())
}
pub fn get_db<'a>() -> &'a PgPool {
DB.get().expect("database not ready")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment