// Copyright © WireMock.Net using Newtonsoft.Json.Linq; using Stef.Validation; namespace WireMock.Matchers.Request; /// /// The request body matcher. /// public class RequestMessageBodyMatcher : IRequestMatcher { private const string _name = nameof(RequestMessageBodyMatcher); /// /// The body data function for type T /// public Func? Func { get; } /// /// The /// public MatchOperator MatchOperator { get; } = MatchOperator.Or; /// /// Initializes a new instance of the class. /// /// The function. public RequestMessageBodyMatcher(Func func) { Func = Guard.NotNull(func); } /// public double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult) { var (score, exception) = CalculateMatchScore(requestMessage).Expand(); return requestMatchResult.AddScore(GetType(), score, exception); } private MatchResult CalculateMatchScore(IRequestMessage requestMessage) { if (Func != null) { if (requestMessage.BodyData?.BodyAsJson is JObject jsonObject) { try { var bodyAsT = jsonObject.ToObject(); return MatchResult.From(_name, MatchScores.ToScore(Func(bodyAsT))); } catch (Exception ex) { return MatchResult.From(_name, ex); } } } return MatchResult.From(_name); } }