Skip to content
Permalink
Browse files
Add server & ajax transit handling
  • Loading branch information
jraines committed Nov 3, 2015
1 parent ee37a09 commit 8e70c146ee3e543f90b7476a202f06a7fd65c354
Showing with 67 additions and 1 deletion.
  1. +19 −0 README.md
  2. +4 −0 project.clj
  3. +17 −1 src/simoutfit/core.cljs
  4. +27 −0 src/simoutfit/server.clj
@@ -42,3 +42,22 @@ I skip that first expression by adding the following to a `dev/user.clj` file an

CSS files inside `resources/public/css` will automatically be reloaded.
You can customize this in the `:figwheel` map of options in the `:cljsbuild` options map in `project.clj`

### Let's fetch some data from a server

Add the following dependencies to `project.clj`

```clojure
[compojure "1.4.0"] ;routing
[http-kit "2.1.19"] ;server
[com.cognitect/transit-clj "0.8.285"] ;transit for clj
[com.cognitect/transit-cljs "0.8.225"] ;transit for cljs
```

We'll use compojure to define the routes our application will respond to and http-kit to be our web server.

Transit is a data format that plays extra nicely with clojure data structures.

In this commit, we set up our server, routes, and add a few helper functions
for writing & reading transit data. Finally we use a library from Google Closure to make an ajax request to fetch some data.

@@ -6,6 +6,10 @@

:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.122"]
[compojure "1.4.0"]
[http-kit "2.1.19"]
[com.cognitect/transit-clj "0.8.285"]
[com.cognitect/transit-cljs "0.8.225"]
[figwheel "0.5.0-SNAPSHOT"]
[figwheel-sidecar "0.5.0-SNAPSHOT"]
[org.clojure/core.async "0.1.346.0-17112a-alpha"]]
@@ -1,12 +1,28 @@
(ns ^:figwheel-always simoutfit.core
(:require))
(:require [cognitect.transit :as t])
(:import [goog.net XhrIo]))

(enable-console-print!)

(println "Edits to this text should show up in your developer console.")

;; define your app data so that it doesn't get over-written on reload

(def r (t/reader :json))

(defn get-data [url cb]
(XhrIo.send url
(fn [e]
(let [xhr (.-target e)]
(cb (.getResponseText xhr))))))

(get-data "/data"
(fn [res]
(println res)
(println (t/read r res))))



(defonce app-state (atom {:text "Hello world!!!"}))


@@ -0,0 +1,27 @@
(ns simoutfit.server
(:require [compojure.core :refer :all]
[compojure.route :as route]
[cognitect.transit :as t]
[org.httpkit.server :refer [run-server]])
(:import [java.io ByteArrayOutputStream]))

(defn write [x]
(let [baos (ByteArrayOutputStream.)
w (t/writer baos :json)
_ (t/write w x)
ret (.toString baos)]
(.reset baos)
ret))

(defn transit-response [x]
{:headers {"Content-Type" "application/transit+json"}
:body (write x)}
)

(defroutes app
(route/resources "/")
(GET "/data" [] (transit-response {"message" "Hello World"})))

(defn -main []
(run-server app {:port 5000}))

0 comments on commit 8e70c14

Please sign in to comment.