Last active
August 29, 2015 14:05
-
-
Save matstani/1fb4b7b94a71780a423b to your computer and use it in GitHub Desktop.
ringハンドラにDatabaseコンポーネントを渡す
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 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 {})) | |
;; requestにDatabaseコンポーネントを追加するミドルウェア | |
(defn wrap-app-component [f db] | |
(fn [req] | |
(f (assoc req :db db)))) | |
;; ミドルウェアを適用したringハンドラを返す関数 | |
(defn make-handler [db] | |
(wrap-app-component app db)) | |
;; HTTPサーバコンポーネント | |
(defrecord HttpServer [port server database] | |
component/Lifecycle | |
(start [this] | |
(if server | |
this | |
(do (println ";; Starting HTTP server") | |
(let [server (run-jetty (make-handler database) | |
{: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