Allow creating and updating tasks on the backend. (#2)
Create hurl tests along with the necessary api code to resolve them. Reviewed-on: #2 Co-authored-by: Drew Galbraith <drew@tiramisu.one> Co-committed-by: Drew Galbraith <drew@tiramisu.one>
This commit is contained in:
parent
82d524a62f
commit
d32f6be813
10 changed files with 306 additions and 28 deletions
|
|
@ -2,20 +2,10 @@ use anyhow::Result;
|
|||
use sqlx::{SqlitePool, sqlite::SqliteConnectOptions};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Database configuration
|
||||
pub struct DatabaseConfig {
|
||||
pub database_url: String,
|
||||
}
|
||||
|
||||
impl Default for DatabaseConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
database_url: "sqlite:local.db".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a SQLx connection pool
|
||||
pub async fn create_pool(config: &DatabaseConfig) -> Result<SqlitePool> {
|
||||
let options = SqliteConnectOptions::from_str(&config.database_url)?.create_if_missing(true);
|
||||
|
||||
|
|
@ -26,12 +16,6 @@ pub async fn create_pool(config: &DatabaseConfig) -> Result<SqlitePool> {
|
|||
Ok(pool)
|
||||
}
|
||||
|
||||
/// Initialize database with connection pool
|
||||
pub async fn initialize_database() -> Result<SqlitePool> {
|
||||
let config = DatabaseConfig::default();
|
||||
create_pool(&config).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub async fn create_test_pool() -> Result<SqlitePool> {
|
||||
let options = SqliteConnectOptions::from_str("sqlite::memory:")?.create_if_missing(true);
|
||||
|
|
@ -42,4 +26,3 @@ pub async fn create_test_pool() -> Result<SqlitePool> {
|
|||
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,23 @@
|
|||
use axum::{Router, routing::get};
|
||||
|
||||
mod models;
|
||||
mod database;
|
||||
mod models;
|
||||
mod services;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let app = Router::new().route("/health", get(health));
|
||||
let binding = database::DatabaseConfig {
|
||||
database_url: "sqlite:local.db".to_string(),
|
||||
};
|
||||
let pool = database::create_pool(&binding)
|
||||
.await
|
||||
.expect("Failed to create database pool");
|
||||
let app = Router::new()
|
||||
.route("/health", get(health))
|
||||
.nest("/api/tasks", services::create_task_router())
|
||||
.with_state(pool);
|
||||
|
||||
let addr = "127.0.0.1:3000";
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ use serde::{Deserialize, Serialize};
|
|||
use sqlx::SqlitePool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::services::AppError;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, sqlx::Type)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[sqlx(rename_all = "lowercase")]
|
||||
|
|
@ -13,7 +15,7 @@ pub enum TaskStatus {
|
|||
Backlog,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
#[derive(sqlx::FromRow, Serialize)]
|
||||
pub struct TaskModel {
|
||||
pub id: Uuid,
|
||||
pub title: String,
|
||||
|
|
@ -46,15 +48,19 @@ impl TaskModel {
|
|||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn get_by_id(pool: &SqlitePool, id: Uuid) -> Result<TaskModel> {
|
||||
let result = sqlx::query_as("SELECT * FROM tasks WHERE id = $1")
|
||||
pub async fn get_by_id(pool: &SqlitePool, id: Uuid) -> Result<TaskModel, AppError> {
|
||||
let model = sqlx::query_as("SELECT * FROM tasks WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(result)
|
||||
.await
|
||||
.map_err(|err| match err {
|
||||
sqlx::Error::RowNotFound => AppError::NotFound,
|
||||
e => anyhow::Error::from(e).into(),
|
||||
})?;
|
||||
Ok(model)
|
||||
}
|
||||
|
||||
pub async fn update(self, pool: &SqlitePool) -> Result<TaskModel> {
|
||||
pub async fn update(self, pool: &SqlitePool) -> Result<TaskModel, AppError> {
|
||||
let now: DateTime<Utc> = Utc::now();
|
||||
|
||||
let _ = sqlx::query(
|
||||
|
|
|
|||
82
backend/src/services/mod.rs
Normal file
82
backend/src/services/mod.rs
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
mod tasks;
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
extract::rejection::{JsonRejection, PathRejection},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
};
|
||||
|
||||
// AppError
|
||||
// Borrowed from example: https://github.com/tokio-rs/axum/blob/axum-v0.8.4/examples/anyhow-error-response/src/main.rs
|
||||
pub enum AppError {
|
||||
InternalError(anyhow::Error),
|
||||
JsonExtractError(JsonRejection),
|
||||
PathError(PathRejection),
|
||||
NotFound,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ErrorJson {
|
||||
error: String,
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
match self {
|
||||
Self::InternalError(anyhow_error) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Something went wrong {}", anyhow_error),
|
||||
)
|
||||
.into_response(),
|
||||
Self::JsonExtractError(rej) => (
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
Json(ErrorJson {
|
||||
error: rej.status().to_string(),
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
Self::PathError(rej) => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(ErrorJson {
|
||||
error: rej.status().to_string(),
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
Self::NotFound => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(ErrorJson {
|
||||
error: "Requeted Entity Not Found".to_string(),
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonRejection> for AppError {
|
||||
fn from(value: JsonRejection) -> Self {
|
||||
Self::JsonExtractError(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathRejection> for AppError {
|
||||
fn from(value: PathRejection) -> Self {
|
||||
Self::PathError(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<anyhow::Error> for AppError {
|
||||
fn from(err: anyhow::Error) -> Self {
|
||||
Self::InternalError(err.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for AppError {
|
||||
fn from(err: sqlx::Error) -> Self {
|
||||
Self::InternalError(err.into())
|
||||
}
|
||||
}
|
||||
|
||||
use serde::Serialize;
|
||||
pub use tasks::*;
|
||||
47
backend/src/services/tasks.rs
Normal file
47
backend/src/services/tasks.rs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
routing::{get, post},
|
||||
};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use axum_macros::debug_handler;
|
||||
use serde::Deserialize;
|
||||
use sqlx::{Pool, Sqlite};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::TaskModel;
|
||||
|
||||
use super::AppError;
|
||||
|
||||
pub fn create_task_router() -> Router<Pool<Sqlite>> {
|
||||
Router::new()
|
||||
.route("/", post(create_task))
|
||||
.route("/{task_id}", get(get_task))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CreateTaskRequest {
|
||||
title: String,
|
||||
description: Option<String>,
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn create_task(
|
||||
State(pool): State<Pool<Sqlite>>,
|
||||
WithRejection(Json(input), _): WithRejection<Json<CreateTaskRequest>, AppError>,
|
||||
) -> Result<(StatusCode, Json<TaskModel>), AppError> {
|
||||
let model = TaskModel::insert(&pool, &input.title, input.description.as_deref()).await?;
|
||||
|
||||
Ok((StatusCode::CREATED, Json(model)))
|
||||
}
|
||||
|
||||
pub async fn get_task(
|
||||
State(pool): State<Pool<Sqlite>>,
|
||||
WithRejection(Path(task_id), _): WithRejection<Path<Uuid>, AppError>,
|
||||
) -> Result<(StatusCode, Json<TaskModel>), AppError> {
|
||||
let model = TaskModel::get_by_id(&pool, task_id).await?;
|
||||
|
||||
Ok((StatusCode::OK, Json(model)))
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue