Created
February 28, 2019 11:12
-
-
Save chamook/e3eddb01718aae12c3348e23c409d6f7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let tryGetPropertyName<'a> propertyName = | |
FSharpType.GetRecordFields typeof<'a> | |
|> Array.tryFind | |
(fun x -> String.Equals(x.Name, propertyName, StringComparison.OrdinalIgnoreCase)) | |
|> Option.map (fun x -> x.Name) | |
let includingRegex = Regex("including=(.*?)(\Z|\0)") | |
let (|FilteredRepresentation|_|) (accept : string option) = | |
match accept with | |
| Some a | |
when a.StartsWith "application/vnd.chamook.api+json" | |
&& a.Contains "including=" -> | |
includingRegex.Match(a).Groups.[1].Captures.[0].Value.Split ',' | |
|> Array.map tryGetPropertyName<Colour> | |
|> Array.choose id | |
|> Array.toList | |
|> Some | |
| _ -> None | |
let filterJson (includeFields : string list) (original : JObject) = | |
let json = JObject() | |
includeFields | |
|> List.iter (fun name -> json.[name] <- original.[name]) | |
json | |
let getMyColours: HttpHandler = | |
fun next ctx -> | |
match ctx.TryGetRequestHeader "Accept" with | |
| FilteredRepresentation filter -> | |
let response = JObject() | |
let colourArray = | |
myColours | |
|> List.map (JObject.FromObject >> filterJson filter) | |
response.["colours"] <- JArray(colourArray) | |
Successful.OK | |
response | |
next | |
ctx | |
| _ -> | |
Successful.OK | |
{ Colours = myColours } | |
next | |
ctx |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment