use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::{JmapError, MethodErrorType};
pub const PROBLEM_JSON: &str = "application/problem+json";
pub const JMAP_ERROR_URN_PREFIX: &str = "urn:ietf:params:jmap:error:";
pub const ABOUT_BLANK: &str = "about:blank";
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProblemDetails {
#[serde(rename = "type", default = "about_blank")]
pub problem_type: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instance: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<String>,
#[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
pub extra: Map<String, Value>,
}
fn about_blank() -> String {
ABOUT_BLANK.to_owned()
}
impl ProblemDetails {
pub fn new(problem_type: impl Into<String>, status: u16) -> Self {
Self {
problem_type: problem_type.into(),
status: Some(status),
title: None,
detail: None,
instance: None,
limit: None,
extra: Map::new(),
}
}
pub fn for_status(status: u16) -> Self {
Self::new(ABOUT_BLANK, status)
}
pub fn for_jmap_error(err: &JmapError, status: u16) -> Self {
let mut p = Self::new(format!("{JMAP_ERROR_URN_PREFIX}{}", err.error_type), status);
p.detail = err.description.clone();
if err.error_type == MethodErrorType::Limit {
p.limit = Some(
err.limit_name
.clone()
.unwrap_or_else(|| "unknown".to_owned()),
);
}
p
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
self.detail = Some(detail.into());
self
}
#[must_use]
pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
self.instance = Some(instance.into());
self
}
pub fn jmap_error_type(&self) -> Option<MethodErrorType> {
self.problem_type
.strip_prefix(JMAP_ERROR_URN_PREFIX)
.map(MethodErrorType::from)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn rfc8620_limit_example_round_trips() {
let body = json!({
"type": "urn:ietf:params:jmap:error:limit",
"limit": "maxSizeRequest",
"status": 400,
"detail": "The request is larger than the server is willing to process."
});
let p: ProblemDetails = serde_json::from_value(body.clone()).unwrap();
assert_eq!(p.jmap_error_type(), Some(MethodErrorType::Limit));
assert_eq!(p.limit.as_deref(), Some("maxSizeRequest"));
assert_eq!(serde_json::to_value(&p).unwrap(), body);
}
#[test]
fn absent_type_is_about_blank() {
let p: ProblemDetails = serde_json::from_value(json!({ "status": 404 })).unwrap();
assert_eq!(p.problem_type, ABOUT_BLANK);
assert_eq!(p.jmap_error_type(), None);
}
#[test]
fn extension_members_round_trip() {
let body = json!({ "type": "about:blank", "requestId": "r1" });
let p: ProblemDetails = serde_json::from_value(body.clone()).unwrap();
assert_eq!(p.extra["requestId"], "r1");
assert_eq!(serde_json::to_value(&p).unwrap(), body);
}
#[test]
fn for_jmap_error_limit_without_name_says_unknown() {
let mut e = JmapError::limit("x");
e.limit_name = None;
assert_eq!(
ProblemDetails::for_jmap_error(&e, 400).limit.as_deref(),
Some("unknown")
);
}
}