Guest User

Untitled

a guest
Dec 27th, 2023
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.99 KB | None | 0 0
  1. use std::sync::Arc;
  2.  
  3. use axum::{
  4. extract::{Path, Query, State},
  5. http::StatusCode,
  6. response::IntoResponse,
  7. Json,
  8. };
  9. //use serde_json::json;
  10.  
  11. use crate::{
  12. model::NoteModel,
  13. model::NoteModel2,
  14. schema::{FilterOptions},
  15. AppState,
  16. };
  17.  
  18. pub async fn health_checker_handler() -> impl IntoResponse {
  19. const MESSAGE: &str = "Simple CRUD API with Rust, SQLX, Postgres,and Axum";
  20.  
  21. let json_response = serde_json::json!({
  22. "status": "success",
  23. "message": MESSAGE
  24. });
  25.  
  26. Json(json_response)
  27. }
  28.  
  29. pub async fn note_list_handler(
  30. opts: Option<Query<FilterOptions>>,
  31. State(data): State<Arc<AppState>>,
  32. ) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
  33. let Query(opts) = opts.unwrap_or_default();
  34.  
  35. let limit = opts.limit.unwrap_or(10);
  36. let offset = (opts.page.unwrap_or(1) - 1) * limit;
  37.  
  38. let query_result = sqlx::query_as!(
  39. NoteModel,
  40. "SELECT c.id,c.idclave_nombre,o.fechaproxima_llamada,c.ubicacion,c.nombres,c.apellidos,c.cedula,c.sector,c.empresa,c.acreedor,c.analista,c.sucursal,o.motivo,c.ps,c.fecha_nacimiento,c.nivel,c.sexo,c.usuario,c.notas
  41. FROM tbl_clientes AS c
  42. LEFT JOIN tbl_observaciones AS o ON c.idclave_nombre = o.idclave_nombre
  43. WHERE o.fechaproxima_llamada IS NOT NULL
  44. AND o.fechaproxima_llamada != ''
  45. LIMIT $1 OFFSET $2",
  46. limit as i32,
  47. offset as i32
  48. )
  49. .fetch_all(&data.db)
  50. .await;
  51.  
  52. if query_result.is_err() {
  53. let error_response = serde_json::json!({
  54. "status": "fail",
  55. "message": "Something bad happened while fetching all note items",
  56. });
  57. return Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)));
  58. }
  59.  
  60. let notes = query_result.unwrap();
  61.  
  62. let json_response = serde_json::json!({
  63. "status": "success",
  64. "results": notes.len(),
  65. "clientes": notes
  66. });
  67. Ok(Json(json_response))
  68. }
  69.  
  70. pub async fn comments_list_handler(
  71. Path(id): Path<i64>,
  72. State(data): State<Arc<AppState>>,
  73. ) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
  74. let query_result = sqlx::query_as!(NoteModel2, "SELECT id,idclave_nombre,usuario,fecha_actualiza,motivo,observacion,fechaproxima_llamada
  75. FROM tbl_observaciones
  76. WHERE id = $1", id
  77. )
  78. .fetch_one(&data.db)
  79. .await;
  80.  
  81. match query_result {
  82. Ok(note) => {
  83. // Record found, do something with the `note`
  84. Ok((StatusCode::OK, Json(note)))
  85. }
  86. Err(sqlx::Error::RowNotFound) => {
  87. // No record found
  88. Err((StatusCode::NOT_FOUND, Json("Record not found")))
  89. }
  90. Err(err) => {
  91. // Other error occurred
  92. eprintln!("Error fetching record: {:?}", err);
  93. Err((StatusCode::INTERNAL_SERVER_ERROR, Json("Internal server error")))
  94. }
  95. }
  96. }
  97.  
  98.  
  99.  
  100.  
  101.  
Add Comment
Please, Sign In to add comment