-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestful.fs
44 lines (34 loc) · 1.16 KB
/
Restful.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
namespace VietnetSuaveApp.Rest
open Suave
open Suave.Filters
open Suave.Operators
open Suave.Successful
open Newtonsoft.Json
open Newtonsoft.Json.Serialization
[<AutoOpen>]
module RestFul =
type RestResource<'a> = {
GetAll : unit -> 'a seq
Create: 'a -> 'a
}
let fromJson<'a> json =
JsonConvert.DeserializeObject(json, typeof<'a>) :?> 'a
let getResourceFromReq<'a> (req: HttpRequest) =
let getString rawForm =
System.Text.Encoding.UTF8.GetString(rawForm)
req.rawForm |> getString |> fromJson<'a>
// 'a -> WebPart
let JSON v =
let jsonSerializerSettings = JsonSerializerSettings()
jsonSerializerSettings.ContractResolver <- CamelCasePropertyNamesContractResolver()
JsonConvert.SerializeObject(v, jsonSerializerSettings)
|> OK
>=> Writers.setMimeType "application/json; charset=utf-8"
// string -> RestResource<'a> -> WebPart
let rest resourceName resource =
let resourcePath = "/" + resourceName
let getAll = warbler (fun _ -> resource.GetAll () |> JSON)
path resourcePath >=> choose [
GET >=> getAll
POST >=> request (getResourceFromReq >> resource.Create >> JSON)
]