[BE] Add logging. Log /person/<dni>

master
Araozu 2023-10-25 12:46:32 -05:00
parent 02e3521eb8
commit fe3541ac4c
6 changed files with 87 additions and 12 deletions

39
backend/Cargo.lock generated
View File

@ -130,8 +130,10 @@ version = "0.1.0"
dependencies = [ dependencies = [
"chrono", "chrono",
"dotenvy", "dotenvy",
"env_logger",
"isahc", "isahc",
"lazy_static", "lazy_static",
"log",
"once_cell", "once_cell",
"reqwest", "reqwest",
"rocket", "rocket",
@ -547,6 +549,19 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "env_logger"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0"
dependencies = [
"humantime",
"is-terminal",
"log",
"regex",
"termcolor",
]
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.1" version = "1.0.1"
@ -978,6 +993,12 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]] [[package]]
name = "hyper" name = "hyper"
version = "0.14.27" version = "0.14.27"
@ -2771,6 +2792,15 @@ dependencies = [
"utf-8", "utf-8",
] ]
[[package]]
name = "termcolor"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6093bad37da69aab9d123a8091e4be0aa4a03e4d601ec641c327398315f62b64"
dependencies = [
"winapi-util",
]
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.47" version = "1.0.47"
@ -3298,6 +3328,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "winapi-x86_64-pc-windows-gnu" name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0" version = "0.4.0"

View File

@ -17,5 +17,7 @@ isahc = { version = "1.7.2", features = ["cookies"] }
urlencoding = "2.1.3" urlencoding = "2.1.3"
lazy_static = "1.4.0" lazy_static = "1.4.0"
once_cell = "1.18.0" once_cell = "1.18.0"
log = "0.4.20"
env_logger = "0.10.0"

View File

@ -17,6 +17,8 @@ CREATE TABLE person (
-- Add person_classroom_username -- Add person_classroom_username
ALTER TABLE `person` ADD `person_classroom_username` VARCHAR(30) NULL DEFAULT NULL AFTER `person_classroom_id`; ALTER TABLE `person` ADD `person_classroom_username` VARCHAR(30) NULL DEFAULT NULL AFTER `person_classroom_id`;
-- Make dni unique
ALTER TABLE `person` ADD UNIQUE(`person_dni`);
CREATE TABLE course ( CREATE TABLE course (

View File

@ -1,3 +1,4 @@
use log::{info, error};
use reqwest::Client; use reqwest::Client;
use rocket::http::Status; use rocket::http::Status;
use rocket::serde::json::Json; use rocket::serde::json::Json;
@ -10,13 +11,32 @@ use crate::{db, model::person::Person};
#[get("/person/<dni>")] #[get("/person/<dni>")]
pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) { pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
let db = db(); let db = db();
info!("get person with dni {}", dni);
/* /*
* Search person in DB * Search person in DB
*/ */
if let Ok(person) = Person::get_by_dni(dni).await { match Person::get_by_dni(dni).await {
Ok(person) => {
return (Status::Ok, JsonResult::ok(person)); return (Status::Ok, JsonResult::ok(person));
} }
Err(error) => {
match error {
// Only if the person is not found in DB, continue
sqlx::Error::RowNotFound => (),
// Otherwise, throw an error
_ => {
error!("Error searching person with dni {}: {:?}", dni, error);
return (
Status::InternalServerError,
JsonResult::err(format!("Error buscando persona en DB.")),
);
}
}
}
};
info!("person with dni {} not found in db, search in RENIEC", dni);
/* /*
* Person not found in DB. Search in fake RENIEC API with reqwest * Person not found in DB. Search in fake RENIEC API with reqwest
@ -33,11 +53,12 @@ pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
let reniec_person = match reqwest_result { let reniec_person = match reqwest_result {
Ok(data) => { Ok(data) => {
info!("person with dni {} found in RENIEC", dni);
let person = data.json::<ReniecPerson>().await; let person = data.json::<ReniecPerson>().await;
match person { match person {
Ok(p) => Some(p), Ok(p) => Some(p),
Err(reason) => { Err(reason) => {
eprintln!( error!(
"Error parsing data from fake RENIEC API into ReniecPerson: {:?}", "Error parsing data from fake RENIEC API into ReniecPerson: {:?}",
reason reason
); );
@ -45,19 +66,21 @@ pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
} }
} }
} }
Err(error) => { Err(err) => {
eprintln!("Error fetching person from fake RENIEC API: {:?}", error); error!("Error fetching person from fake RENIEC API: {:?}", err);
None None
} }
}; };
// If person is found in fake RENIEC API, insert to DB and return // If person is found in fake RENIEC API, insert to DB and return
if let Some(p) = reniec_person { if let Some(p) = reniec_person {
info!("Inserting person found in RENIEC into DB");
// Insert person into DB and get last inserted id // Insert person into DB and get last inserted id
let mut tx = match db.begin().await { let mut tx = match db.begin().await {
Ok(t) => t, Ok(t) => t,
Err(err) => { Err(err) => {
eprintln!("Error starting transaction: {:?}", err); error!("Error starting transaction: {:?}", err);
return ( return (
Status::InternalServerError, Status::InternalServerError,
JsonResult::err(format!("Error iniciando transaccion.")), JsonResult::err(format!("Error iniciando transaccion.")),
@ -82,7 +105,7 @@ pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
match tx.commit().await { match tx.commit().await {
Ok(_) => (), Ok(_) => (),
Err(err) => { Err(err) => {
eprintln!("Error commiting transaction: {:?}", err); error!("Error commiting transaction: {:?}", err);
return ( return (
Status::InternalServerError, Status::InternalServerError,
JsonResult::err(format!("Error confirmando transaccion.")), JsonResult::err(format!("Error confirmando transaccion.")),
@ -91,7 +114,7 @@ pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
} }
if let Err(reason) = query_1 { if let Err(reason) = query_1 {
eprintln!("Error inserting person into DB: {:?}", reason); error!("Error inserting person into DB: {:?}", reason);
return ( return (
Status::InternalServerError, Status::InternalServerError,
JsonResult::err(format!("Error insertando a DB.")), JsonResult::err(format!("Error insertando a DB.")),
@ -101,7 +124,7 @@ pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
let inserted_id = match query_2 { let inserted_id = match query_2 {
Ok(value) => value.person_id, Ok(value) => value.person_id,
Err(error) => { Err(error) => {
println!("Error getting last inserted id: {:?}", error); error!("Error getting last inserted id: {:?}", error);
return ( return (
Status::InternalServerError, Status::InternalServerError,
JsonResult::err(format!("Error recuperando ID insertado.")), JsonResult::err(format!("Error recuperando ID insertado.")),
@ -109,6 +132,7 @@ pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
} }
}; };
info!("person inserted into db, returning");
return ( return (
Status::Ok, Status::Ok,
JsonResult::ok(Person { JsonResult::ok(Person {

View File

@ -23,6 +23,7 @@ pub fn db() -> &'static Pool<MySql> {
#[launch] #[launch]
async fn rocket() -> _ { async fn rocket() -> _ {
dotenvy::dotenv().expect("Failed to load .env file"); dotenvy::dotenv().expect("Failed to load .env file");
env_logger::init();
/* /*
Init DB Init DB

View File

@ -1,3 +1,4 @@
use log::error;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::db; use crate::db;
@ -33,9 +34,15 @@ impl Person {
let result = sqlx::query_as!(Person, "SELECT * FROM person WHERE person_dni = ?", dni) let result = sqlx::query_as!(Person, "SELECT * FROM person WHERE person_dni = ?", dni)
.fetch_one(db) .fetch_one(db)
.await?; .await;
Ok(result) match result {
Ok(v) => Ok(v),
Err(e) => {
error!("Error searching person with dni {}: {:?}", dni, e);
Err(e)
}
}
} }
} }