use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use std::collections::BTreeMap;
use crate::document::{Document, Links, MEDIA_TYPE, ResourceObject};
use crate::error::JsonApiError;
pub struct Fetched(pub Document);
impl Fetched {
pub fn one(resource: ResourceObject) -> Self {
Self(Document::single(resource))
}
pub fn many(resources: Vec<ResourceObject>) -> Self {
Self(Document::collection(resources))
}
pub fn page(resources: Vec<ResourceObject>, links: Links, total: Option<usize>) -> Self {
let mut document = Document::collection(resources).with_links(links);
if let Some(total) = total {
document.meta = Some(BTreeMap::from([(
"total".to_string(),
serde_json::Value::from(total),
)]));
}
Self(document)
}
#[must_use]
pub fn in_context(self, ctx: &crate::Context) -> Self {
match ctx.locale() {
Some(locale) => Self(self.0.with_meta("lang", locale.as_str())),
None => self,
}
}
}
pub struct Created(pub ResourceObject);
#[cfg(feature = "streaming")]
#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
pub struct Streamed(
Box<dyn futures_core::Stream<Item = Result<Vec<u8>, std::convert::Infallible>> + Send + Unpin>,
);
#[cfg(feature = "streaming")]
impl Streamed {
pub fn new(
lines: impl futures_core::Stream<Item = Result<Vec<u8>, std::convert::Infallible>>
+ Send
+ Unpin
+ 'static,
) -> Self {
Self(Box::new(lines))
}
pub fn line(resource: &crate::document::ResourceObject) -> Vec<u8> {
match serde_json::to_vec(resource) {
Ok(mut line) => {
line.push(b'\n');
line
}
Err(_) => Self::error_line(&JsonApiError::new(crate::ErrorCode::Internal)),
}
}
pub fn result_line(resource: &crate::document::ResourceObject) -> Vec<u8> {
match serde_json::to_vec(&Document::single(resource.clone())) {
Ok(mut line) => {
line.push(b'\n');
line
}
Err(_) => Self::error_line(&JsonApiError::new(crate::ErrorCode::Internal)),
}
}
pub fn error_line_at(error: &JsonApiError, line: usize) -> Vec<u8> {
let mut object = error.to_object();
let meta = object.meta.get_or_insert_with(Default::default);
meta.insert(
crate::jsonl::LINE_MEMBER.to_string(),
serde_json::Value::from(line),
);
let document = Document::errors(vec![object]);
let mut rendered = serde_json::to_vec(&document).unwrap_or_else(|_| {
br#"{"errors":[{"status":"500","code":"internal","title":"Internal server error"}]}"#
.to_vec()
});
rendered.push(b'\n');
rendered
}
pub fn error_line(error: &JsonApiError) -> Vec<u8> {
let document = Document::errors(vec![error.to_object()]);
let mut line = serde_json::to_vec(&document).unwrap_or_else(|_| {
br#"{"errors":[{"status":"500","code":"internal","title":"Internal server error"}]}"#
.to_vec()
});
line.push(b'\n');
line
}
}
#[cfg(feature = "streaming")]
impl IntoResponse for Streamed {
fn into_response(self) -> Response {
let body = axum::body::Body::from_stream(self.0);
(
StatusCode::OK,
[
(header::CONTENT_TYPE, crate::jsonl::MEDIA_TYPE),
(header::VARY, "Accept"),
],
body,
)
.into_response()
}
}
pub struct Download {
bytes: Vec<u8>,
content_type: String,
filename: Option<String>,
inline: bool,
}
impl Download {
pub fn new(bytes: impl Into<Vec<u8>>, content_type: impl Into<String>) -> Self {
Self {
bytes: bytes.into(),
content_type: content_type.into(),
filename: None,
inline: false,
}
}
#[must_use]
pub fn filename(mut self, filename: impl Into<String>) -> Self {
self.filename = Some(filename.into());
self
}
#[must_use]
pub fn inline(mut self) -> Self {
self.inline = true;
self
}
}
impl IntoResponse for Download {
fn into_response(self) -> Response {
let mut headers = axum::http::HeaderMap::new();
let content_type = self
.content_type
.parse()
.unwrap_or_else(|_| axum::http::HeaderValue::from_static("application/octet-stream"));
headers.insert(header::CONTENT_TYPE, content_type);
if let std::result::Result::Ok(value) =
disposition(self.inline, self.filename.as_deref()).parse()
{
headers.insert(header::CONTENT_DISPOSITION, value);
}
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
axum::http::HeaderValue::from_static("nosniff"),
);
(StatusCode::OK, headers, self.bytes).into_response()
}
}
pub fn disposition(inline: bool, filename: Option<&str>) -> String {
let kind = if inline { "inline" } else { "attachment" };
let Some(name) = filename else {
return kind.to_string();
};
let mut ascii = String::with_capacity(name.len());
for ch in name.chars() {
match ch {
'"' | '\\' => {
ascii.push('\\');
ascii.push(ch);
}
c if c.is_ascii_graphic() || c == ' ' => ascii.push(c),
_ => ascii.push('_'),
}
}
let mut encoded = String::with_capacity(name.len());
for byte in name.as_bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
encoded.push(*byte as char);
}
other => encoded.push_str(&format!("%{other:02X}")),
}
}
format!("{kind}; filename=\"{ascii}\"; filename*=UTF-8''{encoded}")
}
pub struct NoContent;
impl IntoResponse for Fetched {
fn into_response(self) -> Response {
json_api(StatusCode::OK, &self.0, None)
}
}
impl IntoResponse for Created {
fn into_response(self) -> Response {
let location = self.0.links.as_ref().and_then(|l| l.this.clone());
json_api(StatusCode::CREATED, &Document::single(self.0), location)
}
}
impl IntoResponse for NoContent {
fn into_response(self) -> Response {
(StatusCode::NO_CONTENT, [(header::CONTENT_TYPE, MEDIA_TYPE)]).into_response()
}
}
#[derive(Debug)]
pub struct Errors(pub Vec<JsonApiError>);
impl From<Vec<JsonApiError>> for Errors {
fn from(errors: Vec<JsonApiError>) -> Self {
Self(errors)
}
}
impl From<JsonApiError> for Errors {
fn from(error: JsonApiError) -> Self {
Self(vec![error])
}
}
impl IntoResponse for Errors {
fn into_response(self) -> Response {
let status = self
.0
.iter()
.map(|error| error.status())
.max()
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let objects = self.0.iter().map(JsonApiError::to_object).collect();
let document = with_lang(Document::errors(objects), self.0.first());
json_api(status, &document, None)
}
}
impl IntoResponse for JsonApiError {
fn into_response(self) -> Response {
let status = self.status();
let document = with_lang(Document::errors(vec![self.to_object()]), Some(&self));
json_api(status, &document, None)
}
}
fn with_lang(document: Document, error: Option<&JsonApiError>) -> Document {
match error.and_then(JsonApiError::locale) {
Some(locale) => document.with_meta("lang", locale.as_str()),
None => document,
}
}
fn json_api(status: StatusCode, doc: &Document, location: Option<String>) -> Response {
let body = serde_json::to_string(doc).unwrap_or_else(|_| {
r#"{"errors":[{"status":"500","code":"internal","title":"Internal server error"}]}"#
.to_string()
});
let mut response = (status, [(header::CONTENT_TYPE, MEDIA_TYPE)], body).into_response();
if let Some(location) = location
&& let std::result::Result::Ok(value) = location.parse()
{
response.headers_mut().insert(header::LOCATION, value);
}
response
}