stubr/model/request/body/
json_path_eq.rs1use crate::error::StubrResult;
2use crate::wiremock::{Match, Request};
3use crate::StubrError;
4use serde_json::Value;
5
6use super::{
7 super::json::{json_path_eq::JsonPathEqMatcher, JsonMatcher},
8 BodyMatcherStub,
9};
10
11pub struct JsonBodyPathEqMatcher(String, Value);
12
13impl JsonBodyPathEqMatcher {
14 pub fn matching_json_path_eq(&self, bytes: &[u8]) -> bool {
15 serde_json::from_slice::<Value>(bytes)
16 .ok()
17 .as_ref()
18 .map(|json| JsonPathEqMatcher(&self.0, &self.1).matches(json))
19 .unwrap_or_default()
20 }
21}
22
23impl Match for JsonBodyPathEqMatcher {
24 fn matches(&self, req: &Request) -> bool {
25 self.matching_json_path_eq(&req.body)
26 }
27}
28
29impl TryFrom<&BodyMatcherStub> for JsonBodyPathEqMatcher {
30 type Error = StubrError;
31
32 fn try_from(body: &BodyMatcherStub) -> StubrResult<Self> {
33 body.expression
34 .as_ref()
35 .filter(|_| body.is_by_json_path_eq())
36 .and_then(|path| body.equal_to_json.as_ref().map(|eq| (path, eq)))
37 .map(|(path, eq)| Self(path.to_string(), eq.to_owned()))
38 .ok_or_else(|| StubrError::QuietError)
39 }
40}