Skip to content

Commit

Permalink
feat(ExampleProject): add HttpRequest example (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
m31coding authored Jun 17, 2024
1 parent fe7bc7d commit 790e19c
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/ExampleProject/HttpRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Non-nullable member is uninitialized
#pragma warning disable CS8618
// ReSharper disable All

// Example from https://github.com/dotnet/csharplang/discussions/7325.

using System.Net.Http.Json;
using System.Text.Json;
using M31.FluentApi.Attributes;

namespace ExampleProject;

[FluentApi]
public class HttpRequest
{
[FluentMember(0)]
public HttpMethod Method { get; private set; }

[FluentMember(1)]
public string Url { get; private set; }

[FluentCollection(2, "Header")]
public List<(string, string)> Headers { get; private set; }

[FluentMember(3)]
public HttpContent Content { get; private set; }

[FluentMethod(3)]
public void WithJsonContent<T>(T body, Action<JsonSerializerOptions>? configureSerializer = null)
{
JsonSerializerOptions options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
configureSerializer?.Invoke(options);
Content = new StringContent(JsonSerializer.Serialize(body));
}

[FluentMethod(4)]
[FluentReturn]
public HttpRequestMessage GetMessage()
{
HttpRequestMessage request = new HttpRequestMessage(Method, Url);
request.Content = Content;
Headers.ForEach(h => request.Headers.Add(h.Item1, h.Item2));
return request;
}
}
16 changes: 16 additions & 0 deletions src/ExampleProject/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,22 @@

Console.WriteLine(JsonSerializer.Serialize(employee));

// HttpRequest
//
// Example from https://github.com/dotnet/csharplang/discussions/7325.
//

HttpRequestMessage message = CreateHttpRequest
.WithMethod(HttpMethod.Post)
.WithUrl("https://example.com")
.WithHeaders(("Accept", "application/json"), ("Authorization", "Bearer x"))
.WithJsonContent(
new { Name = "X", Quantity = 10 },
opt => opt.PropertyNameCaseInsensitive = true)
.GetMessage();

Console.WriteLine(JsonSerializer.Serialize(message));

// Node
//

Expand Down

0 comments on commit 790e19c

Please sign in to comment.