summaryrefslogtreecommitdiff
path: root/bs5/universal/native/shared/ServerFunctions.re
blob: acadbd19fe76d64c137191cdb87f0144899b8140 (plain)
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
open Melange_json.Primitives;

module Notes = {
  [@react.server.function]
  let create = (~title: string, ~content: string): Js.Promise.t(Note.t) => {
    let note = DB.add_note(~title, ~content);
    let%lwt response =
      switch%lwt (note) {
      | Ok(note) => Lwt.return(note)
      | Error(e) => failwith(e)
      };
    Lwt.return(response);
  };

  [@react.server.function]
  let edit =
      (~id: int, ~title: string, ~content: string): Js.Promise.t(Note.t) => {
    let note = DB.edit_note(~id, ~title, ~content);
    let%lwt response =
      switch%lwt (note) {
      | Ok(note) => Lwt.return(note)
      | Error(e) => failwith(e)
      };

    Lwt.return(response);
  };

  [@react.server.function]
  let delete_ = (~id: int): Js.Promise.t(string) => {
    let _ = DB.delete_note(id);
    Lwt.return("Note deleted");
  };
};

[@react.server.function]
let simpleResponse = (~name: string, ~age: int): Js.Promise.t(string) => {
  Lwt.return(Printf.sprintf("Hello %s, you are %d years old", name, age));
};

[@react.server.function]
let error = (): Js.Promise.t(string) => {
  // Uncomment to see that it also works with Lwt.fail
  Lwt.fail(
    failwith("Error from server"),
    // failwith(
    //   "Error from server",
    // );
  );
};

[@react.server.function]
let formDataFunction = (formData: Js.FormData.t): Js.Promise.t(string) => {
  let name =
    switch (formData->Js.FormData.get("name")) {
    | `String(name) => name
    | exception _ => failwith("Invalid formData.")
    };

  let response = Printf.sprintf("Form data received: %s", name);

  Lwt.return(response);
};

[@react.server.function]
let formDataWithArg =
    (timestamp: string, formData: Js.FormData.t): Js.Promise.t(string) => {
  let country =
    switch (formData->Js.FormData.get("country")) {
    | `String(country) => country
    };

  let response =
    Printf.sprintf(
      "Form data received: %s, timestamp: %s",
      country,
      timestamp,
    );

  Lwt.return(response);
};