Skip to content

Instantly share code, notes, and snippets.

@willsam100
Created February 21, 2019 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willsam100/50e47ead0f5598875e2052de0acb25bf to your computer and use it in GitHub Desktop.
Save willsam100/50e47ead0f5598875e2052de0acb25bf to your computer and use it in GitHub Desktop.
parseDomainType pure function example
module NotesService
open Newtonsoft.Json
open System
open FSharp.Data
// This type was used for simplicty.
type RestApiResponse = {
StatusCode:int
Body:string
Headers: Map<string,string>
}
// In the real world, HttpResponse from Fsharp.Data is more usefult
// Custom error type
type RestApiError =
| ServerError of response:string
| ClientError of response:string
| MalformedResponse of error:exn
// Our target type - yep we're building a notes apps :)
type Note = {
Created: DateTime
Message: string
}
// This is using FSharp/Data's HttpResponse as the input. You could roll your own, as I
// have shown at the top of the file and in the blog post.
let inline parseDomainType<'a> (response: HttpResponse): Result<'a, RestApiError> =
let body =
match response.Body with
| Binary b -> "" // Assuming this code will never need to handle binary data
| Text t -> t
match response.StatusCode with
| x when x >= 500 && x <= 599 -> body |> ServerError |> Error
| x when x >= 400 && x <= 499 -> body |> ClientError |> Error
| _ ->
try
body |> JsonConvert.DeserializeObject<'a> |> Ok
with
| e -> e |> MalformedResponse |> Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment