/
Cart.fs
99 lines (81 loc) · 2.27 KB
/
Cart.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
module FreyaMusicStore.Cart
open Arachne.Http
open Freya.Core
open Freya.Lenses.Http
open Freya.Machine
open Freya.Machine.Extensions.Http
open Freya.Router
type Item =
{ AlbumId : int
Title : string
Price : decimal
Count : int }
static member fromDb (details : Db.CartDetails) =
{ AlbumId = details.AlbumId
Title = details.AlbumTitle
Price = details.Price
Count = details.Count }
type Cart = {
CartItems : Item []
CartTotal : decimal
}
let id =
freya {
let! id = Freya.getLensPartial (Route.Atom_ "0")
return id
} |> Freya.memo
let ok _=
freya {
let! cartId = id
let ctx = Db.getContext()
let cartDetails = Db.getCartsDetails cartId.Value ctx |> List.toArray
return! writeHtml ("cart", { CartItems = cartDetails |> Array.map Item.fromDb; CartTotal = cartDetails |> Array.sumBy (fun d -> d.Price * (decimal) d.Count) } )
}
let albumId =
freya {
let! form = form
let albumId = form |> Map.tryFind "AlbumId"
return albumId |> Option.bind mInt
} |> Freya.memo
let isMalformed =
freya {
let! meth = Freya.getLens Request.Method_
match meth with
| GET ->
return false
| _ ->
let! albumId = albumId
return albumId.IsNone
}
let post =
freya {
let! albumId = albumId
let! cartId = id
match cartId.Value |> System.Guid.TryParse with
| true, _ ->
do! setResponseCookie "cartId" cartId.Value
| _ ->
()
let ctx = Db.getContext()
Db.addToCart cartId.Value albumId.Value ctx
return ()
}
let delete =
freya {
let! albumId = albumId
let! cartId = id
let ctx = Db.getContext()
let cart = Db.getCart cartId.Value albumId.Value ctx
Db.removeFromCart cart.Value albumId ctx
return ()
}
let pipe =
freyaMachine {
including common
methodsSupported ( freya { return [ GET; POST; DELETE ] } )
handleOk ok
respondWithEntity (Freya.init true)
malformed isMalformed
created (Freya.init false)
doPost post
doDelete delete} |> FreyaMachine.toPipeline