use crate::context::Context;
use crate::document::ResourceObject;
use crate::error::JsonApiError;
use crate::extract::FromRequest;
use crate::query::Query;
use crate::response::Errors;
use crate::validation::DocumentValidator;
pub trait Resource<S: Validators>: Sized + Send + 'static {
type Create: FromRequest<S>;
type Update: FromRequest<S>;
const NAME: &'static str;
const PATH: &'static str;
fn to_resource(&self, state: &S, ctx: &Context) -> Result<ResourceObject, JsonApiError>;
}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not wired up as ash-jsonapi application state",
label = "this state needs a `Validators` impl",
note = "a service that accepts no request bodies needs only an empty impl: `impl ash_jsonapi::crud::Validators for {Self}` with no body",
note = "one that routes CREATE or UPDATE registers its validators instead, with the `ash_jsonapi::registry!` macro"
)]
pub trait Validators: Clone + Send + Sync + 'static {
fn validator(&self, _resource: &str) -> Option<&DocumentValidator> {
None
}
fn hooks(&self) -> Option<&crate::hook::Hooks> {
None
}
}
pub trait Storage<R>: Validators {
type Error: std::fmt::Display + Send;
fn classify(&self, err: &Self::Error, ctx: &Context) -> Option<JsonApiError> {
let _ = (err, ctx);
None
}
fn sortable(&self) -> Option<&[&str]> {
None
}
}
pub trait Create<R: Resource<Self>>: Storage<R> {
fn create(
&self,
input: R::Create,
ctx: &Context,
) -> impl Future<Output = Result<R, Self::Error>> + Send;
}
pub struct Listing<R> {
pub rows: Vec<R>,
pub total: Option<usize>,
pub cursor: Option<String>,
pub has_more: Option<bool>,
}
impl<R> Listing<R> {
pub fn new(rows: impl IntoIterator<Item = R>) -> Self {
Self {
rows: rows.into_iter().collect(),
total: None,
cursor: None,
has_more: None,
}
}
#[must_use]
pub fn total(mut self, total: usize) -> Self {
self.total = Some(total);
self
}
#[must_use]
pub fn has_more(mut self, has_more: bool) -> Self {
self.has_more = Some(has_more);
self
}
#[must_use]
pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
self.cursor = Some(cursor.into());
self
}
}
pub trait List<R: Resource<Self>>: Storage<R> {
fn list(
&self,
query: &Query,
ctx: &Context,
) -> impl Future<Output = Result<Listing<R>, Self::Error>> + Send;
}
pub trait Read<R: Resource<Self>>: Storage<R> {
fn get(&self, id: &str) -> impl Future<Output = Result<Option<R>, Self::Error>> + Send;
}
pub trait Update<R: Resource<Self>>: Storage<R> {
fn update(
&self,
id: &str,
input: R::Update,
ctx: &Context,
) -> impl Future<Output = Result<R, Self::Error>> + Send;
}
#[cfg(feature = "streaming")]
#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
pub trait Stream<R: Resource<Self>>: Storage<R> {
fn stream(
self,
query: Query,
ctx: Context,
) -> impl futures_core::Stream<Item = Result<R, Self::Error>> + Send + Unpin + 'static;
}
#[cfg(feature = "streaming")]
#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
pub trait Ingest<R: Resource<Self>>: Storage<R> {
fn create_one(
&self,
input: R::Create,
ctx: &Context,
) -> impl Future<Output = Result<R, Self::Error>> + Send;
}
#[cfg(feature = "streaming")]
impl<S, R> Ingest<R> for S
where
S: Create<R>,
R: Resource<S>,
{
async fn create_one(&self, input: R::Create, ctx: &Context) -> Result<R, Self::Error> {
self.create(input, ctx).await
}
}
pub trait Content<R: Resource<Self>>: Storage<R> {
fn content(
&self,
id: &str,
) -> impl Future<Output = Result<Option<crate::response::Download>, Self::Error>> + Send;
}
pub trait Delete<R: Resource<Self>>: Storage<R> {
fn destroy(&self, id: &str) -> impl Future<Output = Result<(), Self::Error>> + Send;
}
pub fn validator<'a, S: Validators>(
state: &'a S,
resource: &str,
ctx: &Context,
) -> Result<&'a DocumentValidator, Errors> {
state
.validator(resource)
.ok_or_else(|| logged(ctx, format_args!("resource `{resource}` is not registered")))
}
pub fn before<S: Validators>(
state: &S,
event: &crate::hook::Event<'_>,
ctx: &Context,
) -> Result<(), Errors> {
let Some(hooks) = state.hooks() else {
return Ok(());
};
hooks.before(event, ctx).map_err(Errors::from)
}
pub fn after<S: Validators, T>(
state: &S,
event: &crate::hook::Event<'_>,
ctx: &Context,
result: Result<T, Errors>,
) -> Result<T, Errors> {
let Some(hooks) = state.hooks() else {
return result;
};
let outcome = match &result {
Ok(_) => crate::hook::Outcome::Succeeded {
status: match event.operation {
crate::hook::Operation::Create => 201,
crate::hook::Operation::Delete => 204,
_ => 200,
},
},
Err(errors) => crate::hook::Outcome::Failed {
status: errors
.0
.iter()
.map(|error| error.status().as_u16())
.max()
.unwrap_or(500),
},
};
hooks.after(event, &outcome, ctx);
result
}
pub fn check_sort<S, R>(state: &S, query: &Query, ctx: &Context) -> Result<(), Errors>
where
S: Storage<R>,
{
let Some(sortable) = state.sortable() else {
return Ok(());
};
for key in query.sort() {
if !sortable.contains(&key.field()) {
return Err(
JsonApiError::in_request(crate::ErrorCode::InvalidParameter, ctx)
.detail(format!(
"cannot sort on `{}`; this collection sorts by {}",
key.field(),
sortable
.iter()
.map(|field| format!("`{field}`"))
.collect::<Vec<_>>()
.join(", ")
))
.parameter("sort")
.into(),
);
}
}
Ok(())
}
#[cfg(feature = "streaming")]
pub fn stream_lines<S, R>(state: S, query: Query, ctx: Context) -> crate::response::Streamed
where
S: Stream<R> + Clone + Send + Sync + Unpin + 'static,
R: Resource<S> + Send + 'static,
{
use std::pin::Pin;
use std::task::{Context as TaskContext, Poll};
struct Lines<S, R, F> {
rows: F,
state: S,
ctx: Context,
done: bool,
_row: std::marker::PhantomData<fn() -> R>,
}
impl<S, R, F> futures_core::Stream for Lines<S, R, F>
where
S: Stream<R> + Send + Sync + Unpin + 'static,
R: Resource<S> + Send + 'static,
F: futures_core::Stream<Item = Result<R, S::Error>> + Send + Unpin,
{
type Item = Result<Vec<u8>, std::convert::Infallible>;
fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.done {
return Poll::Ready(None);
}
match Pin::new(&mut this.rows).poll_next(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(None) => {
this.done = true;
Poll::Ready(None)
}
Poll::Ready(Some(Ok(row))) => match row.to_resource(&this.state, &this.ctx) {
Ok(resource) => {
Poll::Ready(Some(Ok(crate::response::Streamed::line(&resource))))
}
Err(error) => {
this.done = true;
Poll::Ready(Some(Ok(crate::response::Streamed::error_line(
&error.in_context(&this.ctx),
))))
}
},
Poll::Ready(Some(Err(err))) => {
this.done = true;
let error = this
.state
.classify(&err, &this.ctx)
.unwrap_or_else(|| JsonApiError::internal(&this.ctx));
Poll::Ready(Some(Ok(crate::response::Streamed::error_line(&error))))
}
}
}
}
let rows = state.clone().stream(query, ctx.clone());
crate::response::Streamed::new(Lines::<S, R, _> {
rows,
state,
ctx,
done: false,
_row: std::marker::PhantomData,
})
}
#[cfg(feature = "streaming")]
pub fn ingest_lines<S, R>(
state: S,
lines: crate::extract::JsonlLines,
ctx: Context,
) -> crate::response::Streamed
where
S: Ingest<R> + Clone + Send + Sync + Unpin + 'static,
R: Resource<S> + Send + 'static,
{
use std::pin::Pin;
use std::task::{Context as TaskContext, Poll};
enum State<R> {
Reading,
Writing(
usize,
Pin<Box<dyn Future<Output = Result<R, Vec<JsonApiError>>> + Send>>,
),
}
struct Ingesting<S, R> {
lines: crate::extract::JsonlLines,
state: S,
ctx: Context,
phase: State<R>,
done: bool,
}
impl<S, R> futures_core::Stream for Ingesting<S, R>
where
S: Ingest<R> + Clone + Send + Sync + Unpin + 'static,
R: Resource<S> + Send + 'static,
{
type Item = Result<Vec<u8>, std::convert::Infallible>;
fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
loop {
if this.done {
return Poll::Ready(None);
}
match &mut this.phase {
State::Writing(number, writing) => {
let number = *number;
let finished = std::task::ready!(writing.as_mut().poll(cx));
this.phase = State::Reading;
let line = match finished {
Ok(row) => match row.to_resource(&this.state, &this.ctx) {
Ok(resource) => crate::response::Streamed::result_line(&resource),
Err(error) => crate::response::Streamed::error_line_at(
&error.in_context(&this.ctx),
number,
),
},
Err(errors) => {
let error = errors
.first()
.cloned()
.unwrap_or_else(|| JsonApiError::internal(&this.ctx));
crate::response::Streamed::error_line_at(&error, number)
}
};
return Poll::Ready(Some(Ok(line)));
}
State::Reading => {
let next = std::task::ready!(Pin::new(&mut this.lines).poll_next(cx));
let (number, line) = match next {
Some(item) => item,
None => {
this.done = true;
return Poll::Ready(None);
}
};
let bytes = match line {
Ok(bytes) => bytes,
Err(error) => {
this.done = true;
return Poll::Ready(Some(Ok(
crate::response::Streamed::error_line_at(&error, number),
)));
}
};
let request = match axum::http::Request::builder()
.method(axum::http::Method::POST)
.header(
axum::http::header::CONTENT_TYPE,
crate::document::MEDIA_TYPE,
)
.body(axum::body::Body::from(bytes))
{
Ok(request) => request,
Err(_) => {
return Poll::Ready(Some(Ok(
crate::response::Streamed::error_line_at(
&JsonApiError::internal(&this.ctx),
number,
),
)));
}
};
let state = this.state.clone();
let ctx = this.ctx.clone();
this.phase = State::Writing(
number,
Box::pin(async move {
type Input<S, R> = <R as Resource<S>>::Create;
let input = <Input<S, R> as FromRequest<S>>::from_request(
request, &state, &ctx,
)
.await
.map_err(|errors| errors.0)?;
state.create_one(input, &ctx).await.map_err(|err| {
match state.classify(&err, &ctx) {
Some(error) => vec![error.in_context(&ctx)],
None => {
eprintln!(
"[{}] ingest failed: {err}",
ctx.correlation_id()
);
vec![JsonApiError::internal(&ctx)]
}
}
})
}),
);
}
}
}
}
}
crate::response::Streamed::new(Ingesting::<S, R> {
lines,
state,
ctx,
phase: State::<R>::Reading,
done: false,
})
}
pub fn failed<S, R>(state: &S, ctx: &Context, stage: &str, err: &S::Error) -> Errors
where
S: Storage<R>,
{
match state.classify(err, ctx) {
Some(error) => error.in_context(ctx).into(),
None => logged(ctx, format_args!("{stage} failed: {err}")),
}
}
fn logged(ctx: &Context, cause: std::fmt::Arguments<'_>) -> Errors {
eprintln!("[{}] {cause}", ctx.correlation_id());
JsonApiError::internal(ctx).into()
}
pub fn missing(ctx: &Context, resource: &str, id: &str) -> Errors {
JsonApiError::in_request(crate::ErrorCode::NotFound, ctx)
.detail(format!("no {resource} with id `{id}`"))
.into()
}
#[macro_export]
macro_rules! api {
(
operations: [$($op:tt)+],
resource: $resource:ident,
name: $name:literal,
path: $base:literal,
state: $state:ident
$(,)?
) => {
pub fn routes() -> ::axum::Router<$state> {
#[allow(unused_mut)]
let mut collection = ::axum::routing::MethodRouter::<$state>::new();
#[allow(unused_mut)]
let mut member = ::axum::routing::MethodRouter::<$state>::new();
#[allow(unused_mut)]
let mut content = ::axum::routing::MethodRouter::<$state>::new();
$crate::__api_routes!(collection, member, content, __api, $($op)+);
$crate::__api_collection_get!(collection, __api, [$($op)+], [$($op)+]);
$crate::__api_collection_post!(collection, __api, [$($op)+], [$($op)+]);
let router = ::axum::Router::new()
.route($base, collection)
.route(::std::concat!($base, "/{id}"), member);
if $crate::__api_has_content!($($op)+) {
router.route(::std::concat!($base, "/{id}/content"), content)
} else {
router
}
}
#[doc(hidden)]
mod __api {
use super::*;
$crate::__api_handlers!($resource, $name, $base, $state, $($op)+);
$crate::__api_maybe_ingest_dispatch!(
$resource, $name, $base, $state, [$($op)+], [$($op)+]
);
use $crate::context::Context;
#[allow(unused_imports)]
use $crate::crud::{
Content as _, Create as _, Delete as _, Read as _, Resource as _, Update as _,
failed, missing,
};
use $crate::extract::FromRequest;
use $crate::response::{Created, Errors, Fetched, NoContent};
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_routes {
($collection:ident, $member:ident, $content:ident, $m:ident $(,)?) => {};
($collection:ident, $member:ident, $content:ident, $m:ident, $prefix:ident :: $($rest:tt)+) => {
$crate::__api_routes!($collection, $member, $content, $m, $($rest)+);
};
($collection:ident, $member:ident, $content:ident, $m:ident, $op:ident $(, $($rest:tt)*)?) => {
$crate::__api_route!($collection, $member, $content, $m, $op);
$($crate::__api_routes!($collection, $member, $content, $m, $($rest)*);)?
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_has_content {
($($op:tt)*) => { $crate::__api_has!(CONTENT, $($op)*) };
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_collection_get {
($collection:ident, $m:ident, [STREAM $(, $($a:tt)*)?], [$($b:tt)*]) => {
$collection = $collection.get($m::list_or_stream);
};
($collection:ident, $m:ident, [$p:ident :: $($a:tt)+], [$($b:tt)*]) => {
$crate::__api_collection_get!($collection, $m, [$($a)+], [$($b)*]);
};
($collection:ident, $m:ident, [$op:ident $(, $($a:tt)*)?], [$($b:tt)*]) => {
$crate::__api_collection_get!($collection, $m, [$($($a)*)?], [$($b)*]);
};
($collection:ident, $m:ident, [], [$($b:tt)*]) => {
$crate::__api_plain_list_get!($collection, $m, $($b)*);
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_plain_list_get {
($collection:ident, $m:ident, LIST $(, $($rest:tt)*)?) => {
$collection = $collection.get($m::list);
};
($collection:ident, $m:ident, CRUD $(, $($rest:tt)*)?) => {
$collection = $collection.get($m::list);
};
($collection:ident, $m:ident, $p:ident :: $($rest:tt)+) => {
$crate::__api_plain_list_get!($collection, $m, $($rest)+);
};
($collection:ident, $m:ident, $op:ident $(, $($rest:tt)*)?) => {
$crate::__api_plain_list_get!($collection, $m, $($($rest)*)?);
};
($collection:ident, $m:ident,) => {};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_has {
($what:ident,) => { false };
($what:ident, $prefix:ident :: $($rest:tt)+) => { $crate::__api_has!($what, $($rest)+) };
($what:ident, $op:ident $(, $($rest:tt)*)?) => {
::std::stringify!($op) == ::std::stringify!($what)
|| $crate::__api_has!($what, $($($rest)*)?)
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_route {
($collection:ident, $member:ident, $content:ident, $m:ident, LIST) => {};
($collection:ident, $member:ident, $content:ident, $m:ident, CREATE) => {};
($collection:ident, $member:ident, $content:ident, $m:ident, READ) => {
$member = $member.get($m::show);
};
($collection:ident, $member:ident, $content:ident, $m:ident, UPDATE) => {
$member = $member.patch($m::update);
};
($collection:ident, $member:ident, $content:ident, $m:ident, DELETE) => {
$member = $member.delete($m::destroy);
};
($collection:ident, $member:ident, $content:ident, $m:ident, CONTENT) => {
$content = $content.get($m::content);
};
($collection:ident, $member:ident, $content:ident, $m:ident, STREAM) => {};
($collection:ident, $member:ident, $content:ident, $m:ident, INGEST) => {};
($collection:ident, $member:ident, $content:ident, $m:ident, CRUD) => {
$member = $member.get($m::show).patch($m::update).delete($m::destroy);
};
($collection:ident, $member:ident, $content:ident, $m:ident, $other:ident) => {
::std::compile_error!(::std::concat!(
"unknown operation `",
::std::stringify!($other),
"`; expected LIST, CREATE, READ, UPDATE, DELETE, CONTENT, STREAM, INGEST or CRUD"
));
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_collection_post {
($collection:ident, $m:ident, [INGEST $(, $($a:tt)*)?], [$($b:tt)*]) => {
$collection = $collection.post($m::create_or_ingest);
};
($collection:ident, $m:ident, [$p:ident :: $($a:tt)+], [$($b:tt)*]) => {
$crate::__api_collection_post!($collection, $m, [$($a)+], [$($b)*]);
};
($collection:ident, $m:ident, [$op:ident $(, $($a:tt)*)?], [$($b:tt)*]) => {
$crate::__api_collection_post!($collection, $m, [$($($a)*)?], [$($b)*]);
};
($collection:ident, $m:ident, [], [$($b:tt)*]) => {
$crate::__api_plain_create_post!($collection, $m, $($b)*);
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_maybe_ingest_dispatch {
($r:ident, $name:literal, $base:literal, $state:ident, [INGEST $(, $($a:tt)*)?], [$($b:tt)*]) => {
$crate::__api_ingest_dispatch!($r, $name, $base, $state, [$($b)*], [$($b)*]);
};
($r:ident, $name:literal, $base:literal, $state:ident, [$p:ident :: $($a:tt)+], [$($b:tt)*]) => {
$crate::__api_maybe_ingest_dispatch!($r, $name, $base, $state, [$($a)+], [$($b)*]);
};
($r:ident, $name:literal, $base:literal, $state:ident, [$op:ident $(, $($a:tt)*)?], [$($b:tt)*]) => {
$crate::__api_maybe_ingest_dispatch!($r, $name, $base, $state, [$($($a)*)?], [$($b)*]);
};
($r:ident, $name:literal, $base:literal, $state:ident, [], [$($b:tt)*]) => {};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_ingest_dispatch {
($r:ident, $name:literal, $base:literal, $state:ident, [CREATE $(, $($a:tt)*)?], [$($b:tt)*]) => {
$crate::__api_dispatch_with_create!($r, $name, $base, $state);
};
($r:ident, $name:literal, $base:literal, $state:ident, [CRUD $(, $($a:tt)*)?], [$($b:tt)*]) => {
$crate::__api_dispatch_with_create!($r, $name, $base, $state);
};
($r:ident, $name:literal, $base:literal, $state:ident, [$p:ident :: $($a:tt)+], [$($b:tt)*]) => {
$crate::__api_ingest_dispatch!($r, $name, $base, $state, [$($a)+], [$($b)*]);
};
($r:ident, $name:literal, $base:literal, $state:ident, [$op:ident $(, $($a:tt)*)?], [$($b:tt)*]) => {
$crate::__api_ingest_dispatch!($r, $name, $base, $state, [$($($a)*)?], [$($b)*]);
};
($r:ident, $name:literal, $base:literal, $state:ident, [], [$($b:tt)*]) => {
$crate::__api_dispatch_ingest_only!($r, $name, $base, $state);
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_dispatch_with_create {
($r:ident, $name:literal, $base:literal, $state:ident) => {
pub async fn create_or_ingest(
state: ::axum::extract::State<$state>,
ctx: ::axum::Extension<Context>,
request: ::axum::extract::Request,
) -> ::axum::response::Response {
use ::axum::response::IntoResponse as _;
let content_type = request
.headers()
.get(::axum::http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(::std::string::ToString::to_string);
if $crate::jsonl::is_jsonl_request(content_type.as_deref()) {
return ingest(state, ctx, request).await;
}
create(state, ctx, request).await.into_response()
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_dispatch_ingest_only {
($r:ident, $name:literal, $base:literal, $state:ident) => {
pub async fn create_or_ingest(
state: ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
request: ::axum::extract::Request,
) -> ::axum::response::Response {
use ::axum::response::IntoResponse as _;
let content_type = request
.headers()
.get(::axum::http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(::std::string::ToString::to_string);
if !$crate::jsonl::is_jsonl_request(content_type.as_deref()) {
return $crate::response::Errors::from(
$crate::JsonApiError::in_request($crate::ErrorCode::UnsupportedMediaType, &ctx)
.detail(::std::concat!(
"this collection accepts batches only; send `",
"application/jsonl",
"`"
)),
)
.into_response();
}
ingest(state, ::axum::Extension(ctx), request).await
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_plain_create_post {
($collection:ident, $m:ident, CREATE $(, $($rest:tt)*)?) => {
$collection = $collection.post($m::create);
};
($collection:ident, $m:ident, CRUD $(, $($rest:tt)*)?) => {
$collection = $collection.post($m::create);
};
($collection:ident, $m:ident, $p:ident :: $($rest:tt)+) => {
$crate::__api_plain_create_post!($collection, $m, $($rest)+);
};
($collection:ident, $m:ident, $op:ident $(, $($rest:tt)*)?) => {
$crate::__api_plain_create_post!($collection, $m, $($($rest)*)?);
};
($collection:ident, $m:ident,) => {};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __api_handlers {
($r:ident, $name:literal, $base:literal, $state:ident $(,)?) => {};
($r:ident, $name:literal, $base:literal, $state:ident, $prefix:ident :: $($rest:tt)+) => {
$crate::__api_handlers!($r, $name, $base, $state, $($rest)+);
};
($r:ident, $name:literal, $base:literal, $state:ident, CRUD $(, $($rest:tt)*)?) => {
$crate::__api_handlers!($r, $name, $base, $state, LIST, CREATE, READ, UPDATE, DELETE);
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
($r:ident, $name:literal, $base:literal, $state:ident, LIST $(, $($rest:tt)*)?) => {
pub async fn list(
::axum::extract::State(state): ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
uri: ::axum::http::Uri,
) -> ::std::result::Result<Fetched, Errors> {
let query = $crate::query::Query::parse(uri.query().unwrap_or_default(), &ctx)?;
$crate::crud::check_sort::<$state, $r>(&state, &query, &ctx)?;
let event = $crate::hook::Event {
operation: $crate::hook::Operation::List,
resource: $name,
id: ::std::option::Option::None,
};
$crate::crud::before(&state, &event, &ctx)?;
let listing = match $crate::crud::List::<$r>::list(&state, &query, &ctx).await {
::std::result::Result::Ok(listing) => listing,
::std::result::Result::Err(err) => {
let errors = failed::<$state, $r>(&state, &ctx, "list", &err);
return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
}
};
let mut resources = ::std::vec::Vec::with_capacity(listing.rows.len());
for row in &listing.rows {
resources.push(row.to_resource(&state, &ctx)?);
}
let links = $crate::query::Paginator::new($base, &query).links(
listing.rows.len(),
listing.total,
listing.cursor.as_deref(),
listing.has_more,
);
$crate::crud::after(
&state,
&event,
&ctx,
::std::result::Result::Ok(
Fetched::page(resources, links, listing.total).in_context(&ctx),
),
)
}
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
($r:ident, $name:literal, $base:literal, $state:ident, CREATE $(, $($rest:tt)*)?) => {
pub async fn create(
::axum::extract::State(state): ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
request: ::axum::extract::Request,
) -> ::std::result::Result<Created, Errors> {
let event = $crate::hook::Event {
operation: $crate::hook::Operation::Create,
resource: $name,
id: ::std::option::Option::None,
};
$crate::crud::before(&state, &event, &ctx)?;
type Input = <$r as $crate::crud::Resource<$state>>::Create;
let input =
match <Input as FromRequest<$state>>::from_request(request, &state, &ctx).await {
::std::result::Result::Ok(input) => input,
::std::result::Result::Err(errors) => {
return $crate::crud::after(
&state, &event, &ctx, ::std::result::Result::Err(errors),
);
}
};
let created = match $crate::crud::Create::<$r>::create(&state, input, &ctx).await {
::std::result::Result::Ok(created) => created,
::std::result::Result::Err(err) => {
let errors = failed::<$state, $r>(&state, &ctx, "create", &err);
return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
}
};
$crate::crud::after(
&state,
&event,
&ctx,
created.to_resource(&state, &ctx).map(Created).map_err(Errors::from),
)
}
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
($r:ident, $name:literal, $base:literal, $state:ident, READ $(, $($rest:tt)*)?) => {
pub async fn show(
::axum::extract::State(state): ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
::axum::extract::Path(id): ::axum::extract::Path<::std::string::String>,
) -> ::std::result::Result<Fetched, Errors> {
let event = $crate::hook::Event {
operation: $crate::hook::Operation::Read,
resource: $name,
id: ::std::option::Option::Some(&id),
};
$crate::crud::before(&state, &event, &ctx)?;
let found = match $crate::crud::Read::<$r>::get(&state, &id).await {
::std::result::Result::Ok(found) => found,
::std::result::Result::Err(err) => {
let errors = failed::<$state, $r>(&state, &ctx, "get", &err);
return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
}
};
let outcome = found
.ok_or_else(|| missing(&ctx, $name, &id))
.and_then(|row| {
row.to_resource(&state, &ctx)
.map(|resource| Fetched::one(resource).in_context(&ctx))
.map_err(Errors::from)
});
$crate::crud::after(&state, &event, &ctx, outcome)
}
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
($r:ident, $name:literal, $base:literal, $state:ident, UPDATE $(, $($rest:tt)*)?) => {
pub async fn update(
::axum::extract::State(state): ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
::axum::extract::Path(id): ::axum::extract::Path<::std::string::String>,
request: ::axum::extract::Request,
) -> ::std::result::Result<Fetched, Errors> {
let event = $crate::hook::Event {
operation: $crate::hook::Operation::Update,
resource: $name,
id: ::std::option::Option::Some(&id),
};
$crate::crud::before(&state, &event, &ctx)?;
type Input = <$r as $crate::crud::Resource<$state>>::Update;
let input =
match <Input as FromRequest<$state>>::from_request(request, &state, &ctx).await {
::std::result::Result::Ok(input) => input,
::std::result::Result::Err(errors) => {
return $crate::crud::after(
&state, &event, &ctx, ::std::result::Result::Err(errors),
);
}
};
let updated = match $crate::crud::Update::<$r>::update(&state, &id, input, &ctx).await {
::std::result::Result::Ok(updated) => updated,
::std::result::Result::Err(err) => {
let errors = failed::<$state, $r>(&state, &ctx, "update", &err);
return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
}
};
$crate::crud::after(
&state,
&event,
&ctx,
updated
.to_resource(&state, &ctx)
.map(|resource| Fetched::one(resource).in_context(&ctx))
.map_err(Errors::from),
)
}
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
($r:ident, $name:literal, $base:literal, $state:ident, STREAM $(, $($rest:tt)*)?) => {
pub async fn list_or_stream(
::axum::extract::State(state): ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
headers: ::axum::http::HeaderMap,
uri: ::axum::http::Uri,
) -> ::axum::response::Response {
use ::axum::response::IntoResponse as _;
let accept = headers
.get(::axum::http::header::ACCEPT)
.and_then(|value| value.to_str().ok());
if !$crate::jsonl::wants_jsonl(accept) {
return list(
::axum::extract::State(state),
::axum::Extension(ctx),
uri,
)
.await
.into_response();
}
let query = match $crate::query::Query::parse(uri.query().unwrap_or_default(), &ctx) {
::std::result::Result::Ok(query) => query,
::std::result::Result::Err(err) => {
return $crate::response::Errors::from(err).into_response();
}
};
if let ::std::result::Result::Err(errors) =
$crate::crud::check_sort::<$state, $r>(&state, &query, &ctx)
{
return errors.into_response();
}
let event = $crate::hook::Event {
operation: $crate::hook::Operation::List,
resource: $name,
id: ::std::option::Option::None,
};
if let ::std::result::Result::Err(errors) =
$crate::crud::before(&state, &event, &ctx)
{
return errors.into_response();
}
let outcome = $crate::crud::after(
&state,
&event,
&ctx,
::std::result::Result::Ok::<(), $crate::response::Errors>(()),
);
if let ::std::result::Result::Err(errors) = outcome {
return errors.into_response();
}
$crate::crud::stream_lines::<$state, $r>(state, query, ctx).into_response()
}
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
($r:ident, $name:literal, $base:literal, $state:ident, INGEST $(, $($rest:tt)*)?) => {
pub async fn ingest(
::axum::extract::State(state): ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
request: ::axum::extract::Request,
) -> ::axum::response::Response {
use ::axum::response::IntoResponse as _;
let event = $crate::hook::Event {
operation: $crate::hook::Operation::Create,
resource: $name,
id: ::std::option::Option::None,
};
if let ::std::result::Result::Err(errors) =
$crate::crud::before(&state, &event, &ctx)
{
return errors.into_response();
}
let outcome = $crate::crud::after(
&state,
&event,
&ctx,
::std::result::Result::Ok::<(), $crate::response::Errors>(()),
);
if let ::std::result::Result::Err(errors) = outcome {
return errors.into_response();
}
let lines = $crate::extract::JsonlLines::new(request, &ctx);
$crate::crud::ingest_lines::<$state, $r>(state, lines, ctx).into_response()
}
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
($r:ident, $name:literal, $base:literal, $state:ident, CONTENT $(, $($rest:tt)*)?) => {
pub async fn content(
::axum::extract::State(state): ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
::axum::extract::Path(id): ::axum::extract::Path<::std::string::String>,
) -> ::std::result::Result<$crate::response::Download, Errors> {
let event = $crate::hook::Event {
operation: $crate::hook::Operation::Read,
resource: $name,
id: ::std::option::Option::Some(&id),
};
$crate::crud::before(&state, &event, &ctx)?;
let found = match $crate::crud::Content::<$r>::content(&state, &id).await {
::std::result::Result::Ok(found) => found,
::std::result::Result::Err(err) => {
let errors = failed::<$state, $r>(&state, &ctx, "content", &err);
return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
}
};
let outcome = found.ok_or_else(|| missing(&ctx, $name, &id));
$crate::crud::after(&state, &event, &ctx, outcome)
}
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
($r:ident, $name:literal, $base:literal, $state:ident, DELETE $(, $($rest:tt)*)?) => {
pub async fn destroy(
::axum::extract::State(state): ::axum::extract::State<$state>,
::axum::Extension(ctx): ::axum::Extension<Context>,
::axum::extract::Path(id): ::axum::extract::Path<::std::string::String>,
) -> ::std::result::Result<NoContent, Errors> {
let event = $crate::hook::Event {
operation: $crate::hook::Operation::Delete,
resource: $name,
id: ::std::option::Option::Some(&id),
};
$crate::crud::before(&state, &event, &ctx)?;
let outcome = $crate::crud::Delete::<$r>::destroy(&state, &id)
.await
.map(|()| NoContent)
.map_err(|err| failed::<$state, $r>(&state, &ctx, "destroy", &err));
$crate::crud::after(&state, &event, &ctx, outcome)
}
$($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
};
}