summaryrefslogtreecommitdiff
path: root/lib/html.ml
blob: 35c7b428ac4f137b720cdd2371e7da7994f94ea5 (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
open Piaf
open Shared

type pool = (Query.conn, Caqti_error.t) Caqti_eio.Pool.t

(* This is the main handler function for the GET /posts endpoint. *)
(* It takes a database connection pool and a Piaf request as input. *)
let get_root (db_pool : pool) (request : Request.t) =
  let _coki = Piaf.Cookies.Cookie.parse request.headers in
  (* Use a connection from the pool. Caqti_eio.Pool.use handles acquiring and releasing the connection. *)
  Caqti_eio.Pool.use
    (fun conn ->
       (* Call the get_poasts function from the Query module to fetch posts from the database. *)
       let posts_or_error = Query.get_poasts () conn in
       (* Pattern match on the result of the database query. *)
       match posts_or_error with
       (* If the query is successful, the result is a list of posts. *)
       | Ok posts ->
         (* Map the list of post tuples to a Yojson list. *)
         let json =
           `List
             ((* For each post tuple, create a JSON object. *)
              List.map
                (fun (post : Query.post_summary) ->
                   `Assoc [ "title", `String post.title ])
                posts)
         in
         (* Return a 200 OK response with the JSON body. *)
         Ok (Response.of_string ~body:(Yojson.Safe.to_string json) `OK)
       (* If the query fails, log the error and return a 500 Internal Server Error response. *)
       | Error err ->
         Logs.err (fun m -> m "Database error: %a" Caqti_error.pp err);
         Ok (Response.create `Internal_server_error))
    db_pool
;;

type paget = ?key:string -> Query.conn -> unit -> React.element

let render_conn (page : paget) (db_pool : pool) (_request : Request.t) =
  (* Caqti_eio.Pool.use *)
  (* (fun conn -> *)
  (* let posts_or = Query.get_poasts () conn in *)
  (* match posts_or with *)
  (* | Error err -> *)
  (* Logs.err (fun m -> m "Database error %a" Caqti_error.pp err); *)
  (* Ok (Response.create `Internal_server_error) *)
  (* | Ok _posts -> Ok (page |> ReactDOM.renderToString |> Http.send_raw_html)) *)
  (* db_pool *)
  Caqti_eio.Pool.use
    (fun conn -> Ok (page conn () |> ReactDOM.renderToString |> Http.send_raw_html))
    db_pool
;;

let render page (_db_pool : pool) (_request : Request.t) =
  Ok (page |> ReactDOM.renderToString |> Http.send_raw_html)
;;