Skip to content

Instantly share code, notes, and snippets.

@wklm wklm/silicon-valley.fs
Last active Sep 14, 2017

Embed
What would you like to do?
Suave + Chrion nested jsons simple example
module Program
open Chiron
open Suave
open Suave.Filters
open Suave.Json
open Suave.Operators
open Suave.Successful
type Role =
{ ID : int
Title : string }
static member ToJson(role : Role) = json {
do! Json.write "id" role.ID
do! Json.write "title" role.Title
}
static member FromJson(_ : Role) = json {
let! i = Json.read "id"
let! t = Json.read "title"
return {
ID = i
Title = t
}
}
type User =
{ ID : int
Role : Role
Name : string
IsAdmin : bool
Supervisor: User option }
static member ToJson(user : User) = json {
do! Json.write "id" user.ID
do! Json.write "role" user.Role
do! Json.write "name" user.Name
do! Json.write "isAdmin" user.IsAdmin
do! Json.write "supervisor" user.Supervisor
}
static member FromJson(_ : User) =
json {
let! i = Json.read "id"
let! r = Json.read "role"
let! n = Json.read "name"
let! a = Json.read "isAdmin"
let! b = Json.read "supervisor"
return {
ID = i
Role = r
Name = n
IsAdmin = a
Supervisor = b
}
}
type UserJson =
| SingleUser of User
| UsersList of list<User>
let getJson u =
match u with
| SingleUser u -> u |> Json.serialize |> Json.format
| UsersList u -> u |> Json.serialize |> Json.format
let richard =
{ ID = 1
Role = { ID = 1
Title = "CEO" }
Name = "Richard"
IsAdmin = true
Supervisor = None }
let erlich =
{ ID = 2
Role = { ID = 2
Title = "Chef Visionary"}
Name = "Erlich"
IsAdmin = true
Supervisor = Some richard }
let jared =
{ ID = 3
Role = { ID = 3
Title = "Accountant"}
Name = "Jared"
IsAdmin = false
Supervisor = Some erlich }
let app =
choose [ GET >=> choose [ path "/" >=> OK ([jared; erlich; richard] |> UsersList |> getJson)
path "/richard" >=> OK (richard |> SingleUser |> getJson)
path "/erlich" >=> OK (erlich |> SingleUser |> getJson)
path "/jared" >=> OK (jared |> SingleUser |> getJson) ]
POST >=> choose [ path "/hello" >=> OK "Hello POST!" ] ]
let myCfg = { defaultConfig with bindings = [ HttpBinding.createSimple HTTP "0.0.0.0" 3000 ] }
[<EntryPoint>]
let main argv =
startWebServer myCfg app
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.