Setup create_task endpoint

This commit is contained in:
Luke Harding 2024-05-03 13:10:48 -04:00
parent f94e356f8e
commit c6edcbd009
3 changed files with 71 additions and 2 deletions

View File

@ -1,11 +1,16 @@
use actix_web::{get, HttpResponse, Responder, web};
use actix_web::{get, HttpResponse, post, Responder, web};
use chrono::NaiveDateTime;
use serde::Deserialize;
use uuid::Uuid;
use crate::api::AppState;
use crate::db;
pub fn configure(cfg: &mut web::ServiceConfig) {
let scope = web::scope("/v1").service(get_task).service(get_tasks);
let scope = web::scope("/v1")
.service(get_task)
.service(get_tasks)
.service(create_task);
cfg.service(scope);
}
@ -31,3 +36,30 @@ pub async fn get_task(data: web::Data<AppState>, path: web::Path<Uuid>) -> impl
HttpResponse::Ok().json(task)
}
#[derive(Deserialize)]
struct JsonTask {
pub title: String,
pub description: String,
pub due_date: NaiveDateTime,
}
#[post("/create_task")]
pub async fn create_task(data: web::Data<AppState>, task: web::Json<JsonTask>) -> impl Responder {
let uuid = Uuid::new_v4();
let new_task = match db::create_task(
data.database_url.clone(),
uuid,
&task.title,
&task.description,
task.due_date,
)
.await
{
Ok(task) => task,
Err(e) => return HttpResponse::InternalServerError().body(e.to_string()),
};
HttpResponse::Ok().json(new_task)
}

View File

@ -3,6 +3,7 @@
use std::error;
use chrono::NaiveDateTime;
use diesel::{
Connection, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl, SelectableHelper,
};
@ -12,6 +13,9 @@ use uuid::Uuid;
use models::Task;
use crate::db::models::NewTask;
use crate::schema::tasks;
pub mod models;
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
@ -43,3 +47,25 @@ pub async fn get_task(database_url: String, uuid: Uuid) -> Result<Task, Box<dyn
Ok(tasks.filter(id.eq(uuid)).first(conn)?)
}
pub async fn create_task(
database_url: String,
uuid: Uuid,
title: &str,
description: &str,
due_date: NaiveDateTime,
) -> Result<Task, Box<dyn error::Error>> {
let conn = &mut establish_connection(&database_url)?;
let new_task = NewTask {
id: uuid,
title,
description,
due_date,
};
Ok(diesel::insert_into(tasks::table)
.values(&new_task)
.returning(Task::as_returning())
.get_result(conn)?)
}

View File

@ -6,6 +6,8 @@ use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::schema::tasks;
#[derive(Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = crate::schema::tasks)]
#[diesel(check_for_backend(diesel::pg::Pg))]
@ -16,3 +18,12 @@ pub struct Task {
pub complete: bool,
pub due_date: NaiveDateTime,
}
#[derive(Insertable, Deserialize, Serialize)]
#[diesel(table_name = tasks)]
pub struct NewTask<'a> {
pub id: Uuid,
pub title: &'a str,
pub description: &'a str,
pub due_date: NaiveDateTime,
}