|
| 1 | +using System.Text; |
| 2 | +using System.Text.Json; |
| 3 | +using System.Text.Json.Serialization; |
| 4 | +using EDILibrary; |
| 5 | +using TransformerBeeClient.Model; |
| 6 | + |
1 | 7 | namespace TransformerBeeClient; |
2 | 8 |
|
3 | 9 | /// <summary> |
4 | 10 | /// a client for the transformer.bee REST API |
5 | 11 | /// </summary> |
6 | | -public class TransformerBeeRestClient |
| 12 | +public class TransformerBeeRestClient : ICanConvertToBo4e |
7 | 13 | { |
8 | 14 | private readonly HttpClient _httpClient; |
| 15 | + private readonly JsonSerializerOptions _jsonSerializerOptions = new() |
| 16 | + { |
| 17 | + PropertyNameCaseInsensitive = true, |
| 18 | + Converters = { new JsonStringEnumConverter() } |
| 19 | + }; |
9 | 20 |
|
10 | 21 | /// <summary> |
11 | 22 | /// Provide the constructor with a http client factory. |
@@ -43,4 +54,39 @@ public async Task<bool> IsAvailable() |
43 | 54 | var response = await _httpClient.GetAsync(versionUrl); |
44 | 55 | return response.IsSuccessStatusCode; |
45 | 56 | } |
| 57 | + |
| 58 | + /// <summary> |
| 59 | + /// convert an edifact to BO4E |
| 60 | + /// </summary> |
| 61 | + /// <param name="edifact">edifact message as string</param> |
| 62 | + /// <param name="formatVersion"><see cref="EdifactFormatVersion"/></param> |
| 63 | + /// <returns><see cref="Marktnachricht"/></returns> |
| 64 | + /// <exception cref="HttpRequestException"></exception> |
| 65 | + public async Task<List<Marktnachricht>> ConvertToBo4e(string edifact, EdifactFormatVersion formatVersion) |
| 66 | + { |
| 67 | + var uriBuilder = new UriBuilder(_httpClient!.BaseAddress) |
| 68 | + { |
| 69 | + Path = "/v1/transformer/EdiToBo4E" |
| 70 | + }; |
| 71 | + |
| 72 | + var convertUrl = uriBuilder.Uri.AbsoluteUri; |
| 73 | + var request = new EdifactToBo4eRequest |
| 74 | + { |
| 75 | + Edifact = edifact, |
| 76 | + FormatVersion = formatVersion, |
| 77 | + }; |
| 78 | + var requestJson = JsonSerializer.Serialize(request, _jsonSerializerOptions); |
| 79 | + var httpResponse = await _httpClient.PostAsync(convertUrl, new StringContent(requestJson, Encoding.UTF8, "application/json")); |
| 80 | + if (!httpResponse.IsSuccessStatusCode) |
| 81 | + { |
| 82 | + throw new HttpRequestException($"Could not convert {edifact} to BO4E. Status code: {httpResponse.StatusCode}"); |
| 83 | + } |
| 84 | + var responseContent = await httpResponse.Content.ReadAsStringAsync(); |
| 85 | + var bo4eResponse = JsonSerializer.Deserialize<EdifactToBo4eResponse>(responseContent, _jsonSerializerOptions); |
| 86 | + // todo: handle the case that the deserialization fails and bo4eResponse is null |
| 87 | + var unescapedJson = bo4eResponse!.Bo4eJsonString.Unescape(); |
| 88 | + var result = JsonSerializer.Deserialize<List<Marktnachricht>>(unescapedJson, _jsonSerializerOptions); |
| 89 | + // todo: handle the case that the deserialization fails and result is null |
| 90 | + return result; |
| 91 | + } |
46 | 92 | } |
0 commit comments