use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::extensible::Extensions;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum PatchOperation {
#[serde(rename = "add")]
Add,
#[serde(rename = "remove")]
Remove,
#[serde(rename = "replace")]
Replace,
#[serde(rename = "move")]
Move,
#[serde(rename = "copy")]
Copy,
#[serde(rename = "test")]
Test,
#[serde(untagged)]
Other(String),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct JsonPatchOp {
pub op: PatchOperation,
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
#[serde(flatten, default, skip_serializing_if = "Extensions::is_empty")]
pub extensions: Extensions,
}
impl JsonPatchOp {
pub fn add(path: impl Into<String>, value: impl Into<Value>) -> Self {
Self {
op: PatchOperation::Add,
path: path.into(),
value: Some(value.into()),
from: None,
extensions: Extensions::new(),
}
}
pub fn replace(path: impl Into<String>, value: impl Into<Value>) -> Self {
Self {
op: PatchOperation::Replace,
path: path.into(),
value: Some(value.into()),
from: None,
extensions: Extensions::new(),
}
}
pub fn remove(path: impl Into<String>) -> Self {
Self {
op: PatchOperation::Remove,
path: path.into(),
value: None,
from: None,
extensions: Extensions::new(),
}
}
pub fn test(path: impl Into<String>, value: impl Into<Value>) -> Self {
Self {
op: PatchOperation::Test,
path: path.into(),
value: Some(value.into()),
from: None,
extensions: Extensions::new(),
}
}
pub fn move_from(from: impl Into<String>, path: impl Into<String>) -> Self {
Self {
op: PatchOperation::Move,
path: path.into(),
value: None,
extensions: Extensions::new(),
from: Some(from.into()),
}
}
pub fn copy_from(from: impl Into<String>, path: impl Into<String>) -> Self {
Self {
op: PatchOperation::Copy,
path: path.into(),
value: None,
extensions: Extensions::new(),
from: Some(from.into()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn remove_op_omits_value() {
let json = serde_json::to_string(&JsonPatchOp::remove("/description")).unwrap();
assert_eq!(json, r#"{"op":"remove","path":"/description"}"#);
}
#[test]
fn move_and_copy_carry_a_source_pointer() {
let moved = JsonPatchOp::move_from("/a", "/b");
assert_eq!(moved.from.as_deref(), Some("/a"));
assert_eq!(moved.path, "/b");
assert!(moved.value.is_none());
}
}