Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
HttpServerコンポーネントはDatabaseコンポーネントを利用する
(ns example-component-ring.component
(:require [com.stuartsierra.component :as component]
[monger.core :as mg]
[example-component-ring.handler :refer [app]]
[ring.adapter.jetty :refer [run-jetty]]))
;; データベースコンポーネント
(defrecord Database [connection]
component/Lifecycle
(start [this]
(if connection
this
(do (println ";; Starting database")
(let [conn (mg/connect)]
(assoc this :connection conn)))))
(stop [this]
(if (not connection)
this
(do (try (mg/disconnect connection)
(catch Throwable t
";; Error when stopping database"))
(println ";; Database stopped")
(assoc this :connection nil)))))
;; データベースコンポーネントの作成用関数
(defn create-database []
(map->Database {}))
;; HTTPサーバコンポーネント
(defrecord HttpServer [port server database]
component/Lifecycle
(start [this]
(if server
this
(do (println ";; Starting HTTP server")
(let [server (run-jetty app
{:port port
:join? false})]
(assoc this :server server)))))
(stop [this]
(if (not server)
this
(do (try (.stop server)
(catch Throwable t
(print ";; Error when stopping HTTP server")))
(println ";; HTTP server stopped")
(assoc this :server nil)))))
;; HTTPサーバコンポーネントの作成用関数
(defn create-http-server [port]
(map->HttpServer {:port port}))
;; システム作成用関数
(defn create-system [config-options]
(let [{:keys [port]} config-options]
(component/system-map
:database (create-database)
:http-server (component/using
(create-http-server port)
[:database]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment