Skip to content

Commit 7faaf01

Browse files
committed
add custom model binder
1 parent ed3d1b2 commit 7faaf01

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

fsharp/ModelBinding/SaturnSample/src/SaturnSample/Program.fs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,26 @@ module Server
33
open Saturn
44
open FSharp.Control.Tasks
55
open Microsoft.AspNetCore.Http
6+
open FsConfig
7+
open System
68

9+
let private camelCaseCanonicalizer _ (name : string) =
10+
name
11+
|> String.mapi (fun i c ->
12+
if (i = 0) then Char.ToLowerInvariant c else c
13+
)
14+
15+
type QueryStringReader(ctx : HttpContext) =
16+
interface IConfigReader with
17+
member __.GetValue name =
18+
printfn "--> %s" name
19+
match ctx.Request.Query.TryGetValue name with
20+
| true, x -> Some (x.ToString())
21+
| _ -> None
22+
23+
let bindQueryString<'T> (ctx : HttpContext) =
24+
let reader = new QueryStringReader(ctx)
25+
parse<'T> reader camelCaseCanonicalizer ""
726

827
type DealsCategory =
928
| AllDeals
@@ -30,17 +49,15 @@ type SearchFilter = {
3049
[<CLIMutable>]
3150
type Search = {
3251
Category : DealsCategory
33-
Filter : SearchFilter option
52+
Filter : SearchFilter
3453
}
3554

3655
type Book = {
3756
Title : string
3857
Author : string
3958
}
4059
let getBooks (ctx : HttpContext) = task {
41-
let qs = ctx.Request.Query
42-
qs |> Seq.iter (printfn "%A")
43-
let search = Controller.getQuery<Search> ctx
60+
let search = bindQueryString<Search> ctx
4461
printfn "%A" search
4562
let response = [{Title = "B1"; Author = "A1"}]
4663
return! Controller.json ctx response
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
FSharp.Core
2-
Saturn
2+
Saturn
3+
FsConfig

0 commit comments

Comments
 (0)