Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removes blocking calls to http stream when using Newtonsoft json #354

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 21 additions & 14 deletions src/Giraffe/Serialization.fs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module Json =
open System.Threading.Tasks
open Newtonsoft.Json
open Newtonsoft.Json.Serialization
open FSharp.Control.Tasks.V2.ContextInsensitive
open Utf8Json

/// **Description**
Expand Down Expand Up @@ -75,9 +76,8 @@ module Json =
/// Serializes objects to camel cased JSON code.
///
type NewtonsoftJsonSerializer (settings : JsonSerializerSettings) =

let serializer = JsonSerializer.Create settings
let Utf8EncodingWithoutBom = new UTF8Encoding(false)
let DefaultBufferSize = 1024

static member DefaultSettings =
JsonSerializerSettings(
Expand All @@ -91,12 +91,16 @@ module Json =
JsonConvert.SerializeObject(x, settings)
|> Encoding.UTF8.GetBytes

member __.SerializeToStreamAsync (x : 'T) (stream : Stream) =
use sw = new StreamWriter(stream, Utf8EncodingWithoutBom, DefaultBufferSize, true)
use jw = new JsonTextWriter(sw)
let sr = JsonSerializer.Create settings
sr.Serialize(jw, x)
Task.CompletedTask
member __.SerializeToStreamAsync (x : 'T) (stream : Stream) =
task {
use memoryStream = new MemoryStream()
use streamWriter = new StreamWriter(memoryStream, Utf8EncodingWithoutBom)
use jsonTextWriter = new JsonTextWriter(streamWriter)
serializer.Serialize(jsonTextWriter, x)
jsonTextWriter.Flush()
memoryStream.Seek(0L, SeekOrigin.Begin) |> ignore
do! memoryStream.CopyToAsync(stream)
} :> Task

member __.Deserialize<'T> (json : string) =
JsonConvert.DeserializeObject<'T>(json, settings)
Expand All @@ -105,12 +109,15 @@ module Json =
let json = Encoding.UTF8.GetString bytes
JsonConvert.DeserializeObject<'T>(json, settings)

member __.DeserializeAsync<'T> (stream : Stream) =
use sr = new StreamReader(stream, true)
use jr = new JsonTextReader(sr)
let sr = JsonSerializer.Create settings
Task.FromResult(sr.Deserialize<'T> jr)

member __.DeserializeAsync<'T> (stream : Stream) =
task {
use memoryStream = new MemoryStream()
do! stream.CopyToAsync(memoryStream)
memoryStream.Seek(0L, SeekOrigin.Begin) |> ignore
use streamReader = new StreamReader(memoryStream)
use jsonTextReader = new JsonTextReader(streamReader)
return serializer.Deserialize<'T>(jsonTextReader)
}
// ---------------------------
// XML
// ---------------------------
Expand Down