Skip to content

Commit

Permalink
Add IHttpContentSerializer and GraphHttpContentSerializer
Browse files Browse the repository at this point in the history
(cherry picked from commit b6f7553)
  • Loading branch information
nozzlegear committed Jan 1, 2025
1 parent b1a98be commit 83e1221
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#if NETSTANDARD2_0
using System.Text;
#else
using System.Buffers;
using System.Net.Http.Headers;
#endif
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;

namespace ShopifySharp.Infrastructure.Serialization.Http;

public class GraphHttpContentSerializer(JsonSerializerOptions jsonSerializerOptions) : IHttpContentSerializer
{
public HttpContent SerializeGraphRequest(RequestUri requestUri, GraphRequest graphRequest)
{
var jsonData = new Dictionary<string, object>
{
{ "query", graphRequest.Query },
{ "variables", graphRequest.Variables },
};

#if NET6_0_OR_GREATER
var bufferWriter = new ArrayBufferWriter<byte>();
using var utf8JsonWriter = new Utf8JsonWriter(bufferWriter);

JsonSerializer.Serialize(utf8JsonWriter, jsonData, jsonSerializerOptions);

var content = new ReadOnlyMemoryContent(bufferWriter.WrittenMemory);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
#else
var jsonStr = JsonSerializer.Serialize(jsonData, jsonSerializerOptions);
const string mediaType = "application/json";
var content = new StringContent(jsonStr, Encoding.UTF8, mediaType);
#endif
return content;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System.Net.Http;

namespace ShopifySharp.Infrastructure.Serialization.Http;

public interface IHttpContentSerializer
{
public HttpContent SerializeGraphRequest(RequestUri requestUri, GraphRequest graphRequest);
}

0 comments on commit 83e1221

Please sign in to comment.