/
Ajax.purs
101 lines (85 loc) · 1.92 KB
/
Ajax.purs
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
100
101
module Oak.Ajax
( module Simple.Ajax
, post
, get
, delete
, put
) where
import Prelude (Unit)
import Simple.JSON (class ReadForeign, class WriteForeign)
import Effect.Aff (Aff, Error, runAff_)
import Data.HTTP.Method (Method(..))
import Effect.Console (errorShow)
import Data.Either (Either(..))
import Simple.Ajax as SA
import Data.MediaType (MediaType(..))
import Affjax.RequestHeader (RequestHeader(..))
import Simple.Ajax (AjaxError)
import Affjax (URL)
import Effect (Effect)
import Data.Maybe
simpleRequest :: ∀ a b.
WriteForeign a
=> ReadForeign b
=> Method
-> URL
-> Maybe a
-> Aff (Either AjaxError b)
simpleRequest m =
SA.simpleRequest
(Left m)
{ headers:
[ Accept (MediaType "application/json")
, ContentType (MediaType "application/json")
]
}
handler :: ∀ a.
ReadForeign a =>
(Either AjaxError a -> Effect Unit)
-> Either Error (Either AjaxError a)
-> Effect Unit
handler h eth =
case eth of
Left e -> errorShow e
Right v -> h v
emptyBody :: Maybe String
emptyBody = Nothing
get :: ∀ a.
ReadForeign a =>
URL
-> (Either AjaxError a -> Effect Unit)
-> Effect Unit
get = mkRequestFun GET emptyBody
delete :: ∀ a.
ReadForeign a =>
URL
-> (Either AjaxError a -> Effect Unit)
-> Effect Unit
delete = mkRequestFun DELETE emptyBody
post :: ∀ a b.
WriteForeign a
=> ReadForeign b
=> Maybe a
-> URL
-> (Either AjaxError b -> Effect Unit)
-> Effect Unit
post = mkRequestFun POST
put :: ∀ a b.
WriteForeign a
=> ReadForeign b
=> Maybe a
-> URL
-> (Either AjaxError b -> Effect Unit)
-> Effect Unit
put = mkRequestFun PUT
mkRequestFun :: ∀ a b.
WriteForeign a
=> ReadForeign b
=> Method
-> Maybe a
-> URL
-> (Either AjaxError b -> Effect Unit)
-> Effect Unit
mkRequestFun meth dat url h =
let fun = simpleRequest meth in do
runAff_ (handler h) (fun url dat)