-
-
Save crinklywrappr/8ff1f0d1db3fdbf86848c2bc9b4e0c8a to your computer and use it in GitHub Desktop.
reloaded workflow with nbb and expresjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns hello-world | |
(:require [integrant.core :as ig] | |
["express$default" :as express] | |
[clojure.tools.cli :as cli])) | |
(def default-port 3000) | |
(def system (atom nil)) | |
(def cli-options | |
[["-p" "--port PORT" "Port number" | |
:default default-port | |
:parse-fn js/Number | |
:validate [#(< 1024 % 0x10000) "Must be a number between 1024 and 65536"]] | |
["-h" "--help"]]) | |
(defn hello-world [count] | |
(fn [_ res] | |
(swap! count inc) | |
(.send res (str "Hello, World! (count: " @count ")")))) | |
(def config | |
{:express/server {:port default-port :app (ig/ref :express/app)} | |
:express/app {:handler hello-world :count (ig/ref ::count)} | |
::count {:start 0}}) | |
(defn start | |
"system is an atom" | |
([] (start config)) | |
([config] (start config system)) | |
([config system] (reset! system (ig/init config)))) | |
(defn stop | |
"system is an atom" | |
([] (stop system)) | |
([system] | |
(when (map? @system) | |
(swap! system ig/halt!)))) | |
(defn exit | |
[& _] | |
(stop) | |
(.exit js/process 0)) | |
(.on js/process "SIGINT" exit) | |
(defmethod ig/init-key :express/app [_ {:keys [handler count]}] | |
(doto (express) | |
(.get "/" (handler count)))) | |
(defmethod ig/init-key :express/server [_ {:keys [port app]}] | |
(.listen app port)) | |
(defmethod ig/init-key ::count [_ {:keys [start]}] | |
(atom start)) | |
(defmethod ig/halt-key! :express/server [_ server] | |
(when (and (some? server) (.-listening server)) | |
(.close server))) | |
(defn print-help [summary] | |
(println "hello world server") | |
(println summary)) | |
(defn print-errors | |
[{:keys [errors summary]}] | |
(doseq [e errors] | |
(println e)) | |
(print-help summary)) | |
(defn start-app [{:keys [port]}] | |
(-> config | |
(assoc-in [:express/server :port] port) | |
start)) | |
(defn handle-args | |
[{:keys [options summary errors] :as args}] | |
(cond | |
(seq errors) (print-errors args) | |
(:help options) (print-help summary) | |
:else (start-app options))) | |
(defn main | |
[& args] | |
(handle-args | |
(cli/parse-opts | |
args cli-options))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment