Added sections route

pull/3/head
Jef Roosens 2021-11-23 20:21:29 +01:00
parent 6013d0bb6e
commit ac7a753dd3
Signed by: Jef Roosens
GPG Key ID: 955C0660072F691F
5 changed files with 112 additions and 17 deletions

View File

@ -5,4 +5,4 @@ pub mod posts;
pub mod sections;
pub use posts::{NewPost, PatchPost, Post};
pub use sections::{NewSection, Section};
pub use sections::{NewSection, PatchSection, Section};

View File

@ -1,5 +1,5 @@
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
use rb::errors::{RbError, RbResult};
use rb::errors::{RbError, RbOption, RbResult};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@ -49,10 +49,19 @@ pub fn get(conn: &PgConnection, offset_: u32, limit_: u32) -> RbResult<Vec<Secti
.map_err(|_| RbError::DbError("Couldn't query sections."))?)
}
pub fn create(conn: &PgConnection, new_post: &NewSection) -> RbResult<Section>
pub fn find_with_shortname(conn: &PgConnection, shortname_: &str) -> RbOption<Section>
{
match sections.filter(shortname.eq(shortname_)).first(conn) {
Ok(val) => Ok(Some(val)),
Err(diesel::NotFound) => Ok(None),
_ => Err(RbError::DbError("Couldn't find section.")),
}
}
pub fn create(conn: &PgConnection, new_section: &NewSection) -> RbResult<Section>
{
Ok(insert_into(sections)
.values(new_post)
.values(new_section)
.get_result(conn)
.map_err(|_| RbError::DbError("Couldn't insert section."))?)
@ -67,6 +76,18 @@ pub fn update(conn: &PgConnection, post_id: &Uuid, patch_post: &PatchSection) ->
.map_err(|_| RbError::DbError("Couldn't update section."))?)
}
pub fn update_with_shortname(
conn: &PgConnection,
shortname_: &str,
patch_section: &PatchSection,
) -> RbResult<Section>
{
Ok(diesel::update(sections.filter(shortname.eq(shortname_)))
.set(patch_section)
.get_result(conn)
.map_err(|_| RbError::DbError("Couldn't update section with shortname."))?)
}
pub fn delete(conn: &PgConnection, post_id: &Uuid) -> RbResult<()>
{
diesel::delete(sections.filter(id.eq(post_id)))

View File

@ -7,7 +7,7 @@ use figment::{
providers::{Env, Format, Yaml},
Figment,
};
use rb::auth::JwtConf;
use rb::{auth::JwtConf, guards};
use rocket::{
fairing::AdHoc,
http::Status,
@ -26,7 +26,7 @@ pub struct RbDbConn(diesel::PgConnection);
#[catch(default)]
fn default_catcher(status: Status, _: &Request) -> Value
{
json!({"status": status.code, "message": "Not found."})
json!({"status": status.code, "message": ""})
}
embed_migrations!();
@ -49,6 +49,9 @@ pub struct RbConfig
jwt: JwtConf,
}
#[get("/test")]
async fn test(_yeet: guards::Jwt) {}
#[launch]
fn rocket() -> _
{
@ -65,8 +68,27 @@ fn rocket() -> _
// .attach(AdHoc::try_on_ignite("Create admin user", create_admin_user))
// .attach(AdHoc::config::<JwtConf>())
.register("/", catchers![default_catcher])
.mount("/sections", routes![sections::create_section])
.mount("/posts", routes![posts::get, posts::create]);
.mount(
"/sections",
routes![
sections::get,
sections::create,
sections::find,
sections::patch,
sections::delete
],
)
.mount(
"/posts",
routes![
posts::get,
posts::create,
posts::find,
posts::patch,
posts::delete
],
)
.mount("/", routes![test]);
let new_figment = rocket.figment();
let jwt_conf: JwtConf = new_figment.extract_inner("jwt").expect("jwt config");

View File

@ -1,20 +1,25 @@
//! This module handles management of site sections (aka blogs).
use rb::{errors::RbResult, guards::Admin};
use rb::{
errors::{RbOption, RbResult},
guards::Admin,
};
use rb_blog::db;
use rocket::serde::json::Json;
use crate::RbDbConn;
/// Route for creating a new section.
///
/// # Arguments
///
/// * `_admin` - guard ensuring user is admin
/// * `conn` - guard providing a connection to the database
/// * `new_section` - Json-encoded NewSection object
#[get("/?<offset>&<limit>")]
pub async fn get(conn: RbDbConn, offset: u32, limit: u32) -> RbResult<Json<Vec<db::Section>>>
{
Ok(Json(
conn.run(move |c| db::sections::get(c, offset, limit))
.await?,
))
}
#[post("/", data = "<new_section>")]
pub async fn create_section(
pub async fn create(
_admin: Admin,
conn: RbDbConn,
new_section: Json<db::NewSection>,
@ -25,3 +30,34 @@ pub async fn create_section(
.await?,
))
}
#[get("/<shortname>")]
pub async fn find(conn: RbDbConn, shortname: String) -> RbOption<Json<db::Section>>
{
Ok(conn
.run(move |c| db::sections::find_with_shortname(c, &shortname))
.await?
.and_then(|p| Some(Json(p))))
}
#[patch("/<shortname>", data = "<patch_section>")]
pub async fn patch(
_admin: Admin,
conn: RbDbConn,
shortname: String,
patch_section: Json<db::PatchSection>,
) -> RbResult<Json<db::Section>>
{
Ok(Json(
conn.run(move |c| {
db::sections::update_with_shortname(c, &shortname, &patch_section.into_inner())
})
.await?,
))
}
#[delete("/<id>")]
pub async fn delete(_admin: Admin, conn: RbDbConn, id: uuid::Uuid) -> RbResult<()>
{
Ok(conn.run(move |c| db::posts::delete(c, &id)).await?)
}

16
test.py 100644
View File

@ -0,0 +1,16 @@
import requests
token = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjVjMjM2OTI0NjY4ZDQzZWFiNGNmNDczYjk1YWZiNzgzIiwidXNlcm5hbWUiOiJKb2huIERvZSIsImFkbWluIjp0cnVlLCJleHAiOjE1MTYyMzkwMjIwfQ.3AzUBe08lcnC3fUIMqPZ8kG51PNPS4MAMpoh_v5HSKM"
headers = {
"Authorization": f"Bearer {token}"
}
print(headers)
data = {
"title": "sometitle",
"shortname": "short",
}
r = requests.get("http://localhost:8000/test", headers=headers)
print(r.content)
print(r.status_code)