| | | 1 | | using System; |
| | | 2 | | using System.Linq; |
| | | 3 | | using HandlebarsDotNet; |
| | | 4 | | using Newtonsoft.Json; |
| | | 5 | | using Newtonsoft.Json.Linq; |
| | | 6 | | using WireMock.Validation; |
| | | 7 | | |
| | | 8 | | namespace WireMock.Transformers |
| | | 9 | | { |
| | | 10 | | internal static class HandleBarsJsonPath |
| | | 11 | | { |
| | | 12 | | public static void Register() |
| | 1 | 13 | | { |
| | 1 | 14 | | Handlebars.RegisterHelper("JsonPath.SelectToken", (writer, context, arguments) => |
| | 5 | 15 | | { |
| | 5 | 16 | | (JObject valueToProcess, string jsonpath) = ParseArguments(arguments); |
| | 1 | 17 | | |
| | 1 | 18 | | try |
| | 5 | 19 | | { |
| | 5 | 20 | | var result = valueToProcess.SelectToken(jsonpath); |
| | 5 | 21 | | writer.WriteSafeString(result); |
| | 5 | 22 | | } |
| | 1 | 23 | | catch (JsonException) |
| | 1 | 24 | | { |
| | 1 | 25 | | // Ignore JsonException |
| | 1 | 26 | | } |
| | 5 | 27 | | }); |
| | | 28 | | |
| | 1 | 29 | | Handlebars.RegisterHelper("JsonPath.SelectTokens", (writer, options, context, arguments) => |
| | 4 | 30 | | { |
| | 4 | 31 | | (JObject valueToProcess, string jsonpath) = ParseArguments(arguments); |
| | 1 | 32 | | |
| | 1 | 33 | | try |
| | 3 | 34 | | { |
| | 3 | 35 | | var values = valueToProcess.SelectTokens(jsonpath); |
| | 3 | 36 | | if (values != null) |
| | 3 | 37 | | { |
| | 11 | 38 | | options.Template(writer, values.ToDictionary(value => value.Path, value => value)); |
| | 3 | 39 | | } |
| | 3 | 40 | | } |
| | 1 | 41 | | catch (JsonException) |
| | 1 | 42 | | { |
| | 1 | 43 | | // Ignore JsonException |
| | 1 | 44 | | } |
| | 3 | 45 | | }); |
| | 1 | 46 | | } |
| | | 47 | | |
| | | 48 | | private static (JObject valueToProcess, string jsonpath) ParseArguments(object[] arguments) |
| | 7 | 49 | | { |
| | 14 | 50 | | Check.Condition(arguments, args => args.Length == 2, nameof(arguments)); |
| | 7 | 51 | | Check.NotNull(arguments[0], "arguments[0]"); |
| | 6 | 52 | | Check.NotNullOrEmpty(arguments[1] as string, "arguments[1]"); |
| | | 53 | | |
| | | 54 | | JObject valueToProcess; |
| | | 55 | | |
| | 6 | 56 | | switch (arguments[0]) |
| | | 57 | | { |
| | | 58 | | case string jsonAsString: |
| | 4 | 59 | | valueToProcess = JObject.Parse(jsonAsString); |
| | 4 | 60 | | break; |
| | | 61 | | |
| | | 62 | | case JObject jsonAsJObject: |
| | 2 | 63 | | valueToProcess = jsonAsJObject; |
| | 2 | 64 | | break; |
| | | 65 | | |
| | | 66 | | default: |
| | 0 | 67 | | throw new NotSupportedException($"The value '{arguments[0]}' with type '{arguments[0]?.GetType()}' c |
| | | 68 | | } |
| | | 69 | | |
| | 6 | 70 | | return (valueToProcess, (string) arguments[1]); |
| | 6 | 71 | | } |
| | | 72 | | } |
| | | 73 | | } |