From 44a35e651741afb6c417da47d636e4380cdd225f Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Sat, 13 Mar 2021 10:17:02 +0100 Subject: feat: add get all repos from db --- src/repository/mod.rs | 2 ++ src/repository/models.rs | 36 ++++++++++++++++++++++++++++++++++++ src/repository/routes.rs | 23 +++++++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 src/repository/mod.rs create mode 100644 src/repository/models.rs create mode 100644 src/repository/routes.rs (limited to 'src/repository') diff --git a/src/repository/mod.rs b/src/repository/mod.rs new file mode 100644 index 0000000..a0e1883 --- /dev/null +++ b/src/repository/mod.rs @@ -0,0 +1,2 @@ +pub mod models; +pub mod routes; diff --git a/src/repository/models.rs b/src/repository/models.rs new file mode 100644 index 0000000..ec5559b --- /dev/null +++ b/src/repository/models.rs @@ -0,0 +1,36 @@ +use crate::db::get_client; +use crate::errors::AppError; +use chrono::NaiveDateTime; +use deadpool_postgres::Pool; +use serde::{Deserialize, Serialize}; +use tokio_pg_mapper::FromTokioPostgresRow; +use tokio_pg_mapper_derive::PostgresMapper; +use uuid::Uuid; + +#[derive(Serialize, Deserialize, PostgresMapper)] +#[pg_mapper(table = "repository")] +pub struct Repository { + pub id: Uuid, + pub url: String, + pub created_at: NaiveDateTime, + pub updated_at: NaiveDateTime, + pub uploader_ip: String, +} + +impl Repository { + pub async fn find_all(pool: Pool) -> Result, AppError> { + let client = get_client(pool.clone()).await.unwrap(); + let statement = client + .prepare("SELECT * FROM repository ORDER BY updated_at DESC") + .await?; + + let repos = client + .query(&statement, &[]) + .await? + .iter() + .map(|row| Repository::from_row_ref(row).unwrap()) + .collect::>(); + + Ok(repos) + } +} diff --git a/src/repository/routes.rs b/src/repository/routes.rs new file mode 100644 index 0000000..ebfff8e --- /dev/null +++ b/src/repository/routes.rs @@ -0,0 +1,23 @@ +use crate::config::AppState; +use crate::repository::models::Repository; +use actix_web::{web, HttpResponse, Responder}; +use slog::info; + +async fn index(state: web::Data) -> impl Responder { + let result = Repository::find_all(state.pool.clone()).await; + match result { + Ok(repos) => { + info!(state.log, "GET /repo/ 200"); + HttpResponse::Ok().json(repos) + } + _ => { + info!(state.log, "GET /repo/ 500"); + HttpResponse::BadRequest() + .body("Error trying to read all repositories from database") + } + } +} + +pub fn config(cfg: &mut web::ServiceConfig) { + cfg.service(web::resource("/repo/").route(web::get().to(index))); +} -- cgit v1.2.3-18-g5258