1+ (ns uix.rsc-example.server.core
2+ (:require [clojure.edn :as edn]
3+ [clojure.java.io :as io]
4+ [uix.core :refer [defui $] :as uix]
5+ [uix.rsc :as rsc]
6+ [org.httpkit.server :as server]
7+ [compojure.core :refer [defroutes GET POST]]
8+ [compojure.route :as route]
9+ [ring.util.response :as resp]
10+ [reitit.core :as r]
11+ [uix.rsc-example.server.root :refer [root]]
12+ [uix.rsc-example.routes :refer [routes]])
13+ (:import (java.io PushbackReader))
14+ (:gen-class ))
15+
16+ (defn read-end-stream [body]
17+ (with-open [reader (io/reader body)]
18+ (edn/read (PushbackReader. reader))))
19+
20+ (def router
21+ (r/router routes))
22+
23+ (defn handler [request]
24+ (let [{:keys [route]} (read-end-stream (:body request))
25+ route (r/match-by-path router (:path route))]
26+ ; ; request -> route -> react flight rows -> response stream
27+ (server/as-channel request
28+ {:on-open (fn [ch]
29+ (let [on-chunk (fn [chunk]
30+ (if (= chunk :done )
31+ (server/close ch)
32+ (server/send! ch chunk false )))]
33+ (rsc/render-to-flight-stream ($ root {:route route})
34+ {:on-chunk on-chunk})))})))
35+
36+ (defroutes server-routes*
37+ ; ; react flight payload endpoint
38+ (POST " /rsc" req
39+ (handler req))
40+ ; ; server actions endpoint
41+ (POST " /api" {body :body }
42+ (try
43+ (-> (rsc/handle-action (read-end-stream body))
44+ str
45+ (resp/response )
46+ (resp/header " Content-Type" " text/edn" ))
47+ (catch Exception e
48+ (-> (resp/bad-request (ex-message e))
49+ (resp/header " Content-Type" " text/edn" )))))
50+ ; ; static assets
51+ (route/files " /" {:root " ./" })
52+ ; ; always serving index.html instead of 404
53+ (GET " /*" req
54+ ; ; todo: render flight payload into html on initial load
55+ (-> (resp/file-response " index.html" {:root " ./" })
56+ (resp/header " Content-Type" " text/html" ))))
57+
58+ (defn start-server []
59+ (server/run-server #'server-routes* {:port 8080 })
60+ (println " Server is listening at http://localhost:8080" ))
61+
62+ (defn -main [& args]
63+ (start-server ))
64+
65+ (comment
66+ (def stop-server (start-server ))
67+ (stop-server ))
0 commit comments