use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub type JsonPatch = Vec<PatchOperation>;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum PatchOperation {
Add {
path: String,
#[serde(default)]
value: Value,
#[serde(flatten)]
extra: BTreeMap<String, Value>,
},
Remove {
path: String,
#[serde(flatten)]
extra: BTreeMap<String, Value>,
},
Replace {
path: String,
#[serde(default)]
value: Value,
#[serde(flatten)]
extra: BTreeMap<String, Value>,
},
Move {
from: String,
path: String,
#[serde(flatten)]
extra: BTreeMap<String, Value>,
},
Copy {
from: String,
path: String,
#[serde(flatten)]
extra: BTreeMap<String, Value>,
},
Test {
path: String,
#[serde(default)]
value: Value,
#[serde(flatten)]
extra: BTreeMap<String, Value>,
},
}
impl PatchOperation {
pub fn add(path: impl Into<String>, value: impl Into<Value>) -> Self {
Self::Add {
path: path.into(),
value: value.into(),
extra: BTreeMap::new(),
}
}
pub fn remove(path: impl Into<String>) -> Self {
Self::Remove {
path: path.into(),
extra: BTreeMap::new(),
}
}
pub fn replace(path: impl Into<String>, value: impl Into<Value>) -> Self {
Self::Replace {
path: path.into(),
value: value.into(),
extra: BTreeMap::new(),
}
}
pub fn mv(from: impl Into<String>, path: impl Into<String>) -> Self {
Self::Move {
from: from.into(),
path: path.into(),
extra: BTreeMap::new(),
}
}
pub fn copy(from: impl Into<String>, path: impl Into<String>) -> Self {
Self::Copy {
from: from.into(),
path: path.into(),
extra: BTreeMap::new(),
}
}
pub fn test(path: impl Into<String>, value: impl Into<Value>) -> Self {
Self::Test {
path: path.into(),
value: value.into(),
extra: BTreeMap::new(),
}
}
pub const fn extra(&self) -> &BTreeMap<String, Value> {
match self {
Self::Add { extra, .. }
| Self::Remove { extra, .. }
| Self::Replace { extra, .. }
| Self::Move { extra, .. }
| Self::Copy { extra, .. }
| Self::Test { extra, .. } => extra,
}
}
pub const fn op(&self) -> &'static str {
match self {
Self::Add { .. } => "add",
Self::Remove { .. } => "remove",
Self::Replace { .. } => "replace",
Self::Move { .. } => "move",
Self::Copy { .. } => "copy",
Self::Test { .. } => "test",
}
}
pub fn path(&self) -> &str {
match self {
Self::Add { path, .. }
| Self::Remove { path, .. }
| Self::Replace { path, .. }
| Self::Move { path, .. }
| Self::Copy { path, .. }
| Self::Test { path, .. } => path,
}
}
pub fn from(&self) -> Option<&str> {
match self {
Self::Move { from, .. } | Self::Copy { from, .. } => Some(from),
_ => None,
}
}
pub const fn value(&self) -> Option<&Value> {
match self {
Self::Add { value, .. } | Self::Replace { value, .. } | Self::Test { value, .. } => {
Some(value)
}
_ => None,
}
}
}