Skip to content

Commit

Permalink
feat: add initial wisdoms and way to retrieve it
Browse files Browse the repository at this point in the history
  • Loading branch information
nikola-bozin-org committed Apr 21, 2024
1 parent a9cb02a commit 4e8720e
Show file tree
Hide file tree
Showing 14 changed files with 124 additions and 31 deletions.
Empty file modified .github/workflows/ci.yml
100644 → 100755
Empty file.
5 changes: 5 additions & 0 deletions migrations/0002_initial-wisdoms-population.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
BEGIN TRANSACTION;

DELETE FROM wisdoms WHERE id IN (1, 2, 3);

COMMIT;
7 changes: 7 additions & 0 deletions migrations/0002_initial-wisdoms-population.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
BEGIN TRANSACTION;

INSERT INTO wisdoms (id, description) VALUES (1, 'Patience is a virtue.');
INSERT INTO wisdoms (id, description) VALUES (2, 'Knowledge is power.');
INSERT INTO wisdoms (id, description) VALUES (3, 'Time is money.');

COMMIT;
31 changes: 31 additions & 0 deletions src/db/connect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
pub type Result<T> = core::result::Result<T, Error>;

use sqlx::postgres::PgPoolOptions;
use tracing_fast_dev::tfd;

pub type Database = sqlx::Pool<sqlx::Postgres>;


#[derive(Debug)]
pub enum Error {
FailedConnectingToDatabase { error: String },
}

impl From<sqlx::Error> for Error {
fn from(value: sqlx::Error) -> Self {
Self::FailedConnectingToDatabase {
error: value.to_string(),
}
}
}

pub async fn connect(db_url: &str) -> Result<Database> {
let pool: Database = PgPoolOptions::new()
// TODO: Max connections! Dynamic?
.max_connections(5)
.connect(db_url)
.await?;
tfd().info("CONNECTED", "DATABASE");

Ok(pool)
}
34 changes: 4 additions & 30 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,5 @@
pub type Result<T> = core::result::Result<T, Error>;
mod queries;
mod connect;


use sqlx::postgres::PgPoolOptions;
use tracing_fast_dev::tfd;

pub type Database = sqlx::Pool<sqlx::Postgres>;

#[derive(Debug)]
pub enum Error {
FailedConnectingToDatabase { error: String },
}

impl From<sqlx::Error> for Error {
fn from(value: sqlx::Error) -> Self {
Self::FailedConnectingToDatabase {
error: value.to_string(),
}
}
}

pub async fn connect(db_url: &str) -> Result<Database> {
let pool: Database = PgPoolOptions::new()
// TODO: Max connections! Dynamic?
.max_connections(5)
.connect(db_url)
.await?;
tfd().info("CONNECTED", "DATABASE");

Ok(pool)
}
pub use queries::*;
pub use connect::*;
10 changes: 10 additions & 0 deletions src/db/queries.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use crate::models::Wisdom;
use super::connect::Database;

pub async fn _get_wisdoms(db: &Database) -> Result<Vec<Wisdom>, sqlx::Error> {
tracing_fast_dev::tfd().info("GET_WISDOMS_INTERNAL", "QUERY");
let wisdoms: Vec<Wisdom> = sqlx::query_as("SELECT * from wisdoms")
.fetch_all(db)
.await?;
Ok(wisdoms)
}
10 changes: 10 additions & 0 deletions src/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use axum::{
body::Body,
http::{Response, StatusCode},
response::IntoResponse,
};
pub fn default_handle_error<E: std::fmt::Display>(e: E) -> Response<Body> {
let mut response = (StatusCode::INTERNAL_SERVER_ERROR).into_response();
response.extensions_mut().insert(e.to_string());
response
}
2 changes: 2 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ mod constants;
mod state;
mod db;
mod routes;
mod models;
mod middlewares;
mod helpers;

use state::AppState;
use std::{env, sync::Arc};
Expand Down
12 changes: 12 additions & 0 deletions src/models/dto.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct CreateWisdomDTO {
pub description: String,
}

#[derive(Debug, Deserialize)]
pub struct UpdateWisdomDTO {
pub id: i32,
pub description: String,
}
5 changes: 5 additions & 0 deletions src/models/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod dto;
mod wisdom;

pub use dto::*;
pub use wisdom::*;
8 changes: 8 additions & 0 deletions src/models/wisdom.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use serde::Serialize;
use sqlx::prelude::FromRow;

#[derive(Debug, FromRow, Serialize)]
pub struct Wisdom {
pub id: i32,
pub description: String,
}
5 changes: 4 additions & 1 deletion src/routes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod dbg;
mod wisdoms;

use axum::Router;

Expand All @@ -9,6 +10,8 @@ pub fn routes() -> Router {

fn _routes() -> Router {
let mut router = Router::new();
router = router.merge(dbg::routes());
router = router
.merge(dbg::routes())
.merge(wisdoms::routes());
router
}
25 changes: 25 additions & 0 deletions src/routes/wisdoms.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use std::sync::Arc;

use axum::{http::StatusCode, response::IntoResponse, routing::get, Extension, Json, Router};

use crate::{db::_get_wisdoms, helpers::default_handle_error, state::AppState};

use serde_json::json;

pub fn routes() -> Router {
Router::new().nest("/wisdoms", _routes())
}

fn _routes() -> Router {
Router::new()
.route("/", get(get_wisdoms))
}


async fn get_wisdoms(Extension(state): Extension<Arc<AppState>>) -> impl IntoResponse {
tracing_fast_dev::tfd().info("GET_WISDOM", "FUNCTION");
match _get_wisdoms(&state.db).await {
Ok(wisdoms) => (StatusCode::OK, Json(json!({ "wisdoms": wisdoms }))).into_response(),
Err(e) => default_handle_error(e),
}
}
1 change: 1 addition & 0 deletions src/state.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::db::Database;


#[derive(Clone)]
pub struct AppState {
pub db: Database,
Expand Down

0 comments on commit 4e8720e

Please sign in to comment.