Clojure for JavaScript devs
Posted on . Updated on .
My random notes about Clojure from the eyes of a JavaScript frontend developer.
Learning resources
- Clojure Documentation: Community-driven documentation. Contains up-to-date practices.
- Caveman - A Clojure Web Framework: Building a web framework from the ground up.
- Learn to build a Clojure web app - a step-by-step tutorial: by Eric Normand.
- Clojure for the Brave and True: My first Clojure book. Funnily written. Maybe outdated.
Installation and Clojure CLI
- Use JDK with SDKMan.
Collections
- Remove items:
(filter pred coll),(remove pred coll),(keep f coll).keepwill take only non-nil values of(f item), includingfalse.
Hash map
Construct a hash map:
(hash-map :a 1 :b 2)
(into {} [[:a 1] [:b 2]])
into takes a vector of key-value pairs. Can use it for transformation:
(->> [:a :b :c]
(map-indexed vector)
(into {}))
;; {0 :a 1 :b 2 :c}
Get item from a map:
(def m {:a 1 :b 2})
(:a m)
(get m :a)
(get m :z "default-value")
Pick some keys from the map:
(select-keys user [:user/name :user/id :user/avatar])
Update keys/ vals of a map:
(update-keys {"a" 1 "b" 2} keyword)
;; {:a 1 :b 2}
(update-vals {:a 1 :b 2} inc)
;; {:a 2 :b 3}Deploy to Fly.io
First, build the whole project to uberjar file.
To init a project, run:
$ fly launch
Open fly.toml and change services.internal_port. Assume that your web app is running on port 4001:
[[services]]
protocol = "tcp"
internal_port = 4001
processes = ["app"]
Create Dockerfile having EXPOSE the same port value as services.internal_port.
FROM adoptopenjdk:11-jre-hotspot
RUN mkdir /opt/app
COPY target/uberjar/app.jar /opt/app/app.jar
EXPOSE 4001
CMD ["java", "-jar", "/opt/app/app.jar"]
Then
$ fly deploy