-
Notifications
You must be signed in to change notification settings - Fork 53
/
ocaml_examples.ml
40 lines (37 loc) · 1.2 KB
/
ocaml_examples.ml
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
let _ =
Js.Promise.(
Fetch.fetch "/api/hellos/1"
|> then_ Fetch.Response.text
|> then_ (fun text -> print_endline text |> resolve))
let _ =
Js.Promise.(
Fetch.fetchWithInit "/api/hello" (Fetch.RequestInit.make ~method_:Post ())
|> then_ Fetch.Response.text
|> then_ (fun text -> print_endline text |> resolve))
let _ =
Js.Promise.(
Fetch.fetch "/api/fruit"
(* assume server returns `["apple", "banana", "pear", ...]` *)
|> then_ Fetch.Response.json
|> then_ (fun json -> Js.Json.decodeArray json |> resolve)
|> then_ (fun opt -> Belt.Option.getExn opt |> resolve)
|> then_ (fun items ->
items
|> Js.Array.map (fun item ->
item |> Js.Json.decodeString |> Belt.Option.getExn)
|> resolve))
let _ =
let headers = [%bs.raw {|
{"Content-type": "application/json"}
|}] in
let payload = Js.Dict.empty () in
Js.Dict.set payload "hello" (Js.Json.string "world");
let open Js.Promise in
Fetch.fetchWithInit
"/api/hello"
(Fetch.RequestInit.make
~method_:Post
~body:(Fetch.BodyInit.make (Js.Json.stringify (Js.Json.object_ payload)))
~headers:(Fetch.HeadersInit.make headers)
())
|> then_ Fetch.Response.json