use axum::extract::Request;
use axum::middleware::Next;
use axum::response::Response;
use ash_jsonapi::Context;
use crate::blog::{AUTHORS_PATH, Author, POSTS_PATH, Post};
use crate::store::App;
mod posts {
use super::*;
ash_jsonapi::api! {
operations: [
ash_jsonapi::LIST,
ash_jsonapi::CREATE,
ash_jsonapi::READ,
ash_jsonapi::UPDATE,
ash_jsonapi::DELETE
],
resource: Post,
name: "post",
path: "/posts",
state: App,
}
}
mod authors {
use super::*;
ash_jsonapi::api! {
operations: [ash_jsonapi::LIST, ash_jsonapi::CREATE, ash_jsonapi::READ],
resource: Author,
name: "author",
path: "/authors",
state: App,
}
}
async fn authenticate(mut request: Request, next: Next) -> Response {
let principal = request
.headers()
.get("x-principal")
.and_then(|value| value.to_str().ok())
.map(ToString::to_string);
if let Some(principal) = principal {
if let Some(ctx) = request.extensions().get::<Context>().cloned() {
request
.extensions_mut()
.insert(ctx.with_principal(principal));
}
}
next.run(request).await
}
pub fn app(state: App) -> axum::Router {
axum::Router::new()
.merge(posts::routes())
.merge(authors::routes())
.layer(axum::middleware::from_fn(authenticate))
.layer(ash_jsonapi::layer())
.with_state(state)
}
pub async fn serve(state: App) -> std::io::Result<()> {
println!("listening on http://{ADDR}");
println!();
println!(" GET {POSTS_PATH}");
println!(" POST {POSTS_PATH} (write: needs X-Principal)");
println!(" GET {POSTS_PATH}/{{id}}");
println!(" PATCH {POSTS_PATH}/{{id}} (write: needs X-Principal)");
println!(" DELETE {POSTS_PATH}/{{id}} (write: needs X-Principal)");
println!(" GET {AUTHORS_PATH}");
println!(" POST {AUTHORS_PATH} (write: needs X-Principal)");
println!();
ash_jsonapi::serve!(ADDR, app(state)).await
}
const ADDR: &str = "0.0.0.0:3001";