-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_component.clj
65 lines (53 loc) · 1.67 KB
/
config_component.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
(ns eduardoeof.config-component
(:require [com.stuartsierra.component :as component]
[cheshire.core :as json]
[clj-yaml.core :as yaml]
[clojure.string :as str]
[clojure.edn :as edn]))
(defn- yml? [type]
(= type :yml))
(defn- get-file-format [file-name]
(let [splits (str/split file-name #"\.")]
(if (= 1 (count splits))
:unknown
(-> splits
last
keyword
((fn [format] (if (yml? format) :yaml format)))))))
(defn- parse-yaml [file-name]
(-> file-name
slurp
yaml/parse-string))
(defn- parse-json [file-name]
(-> file-name
slurp
(json/parse-string true)))
(defn- parse-edn [file-name]
(-> file-name
slurp
edn/read-string))
(defn- build-not-supported-exception
[file-name format]
(ex-info "File format not supported"
{:reason :eduardoeof.config-component/file-format-not-supported-exception
:file-name file-name
:format format
:tip (str "Check if the file name has the format explicited (e.g. \".json\") "
"or it is in an unsupported format.")}))
(defn- load-config [file-name]
(let [format (get-file-format file-name)]
(case format
:json (parse-json file-name)
:yaml (parse-yaml file-name)
:edn (parse-edn file-name)
(throw (build-not-supported-exception file-name
format)))))
(defrecord Config [file-name]
component/Lifecycle
(start [this]
(let [config (load-config file-name)]
(merge this config)))
(stop [this]
nil))
(defn new-config [file-name]
(map->Config {:file-name file-name}))