// Copyright © WireMock.Net
using System;
using Newtonsoft.Json.Linq;
using Stef.Validation;
namespace WireMock.Matchers.Request;
///
/// The request body matcher.
///
public class RequestMessageBodyMatcher : IRequestMatcher
{
///
/// 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 MatchScores.ToScore(Func(bodyAsT));
}
catch (Exception ex)
{
return new MatchResult(ex);
}
}
}
return default;
}
}