Quantcast
Channel: Repository pattern in clojure - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by noisesmith for Repository pattern in clojure

$
0
0

1) Group functions by shared subproblems. In our ORM we have a namespace for db interaction, a separate namespace for each target db, a namespace for model construction and query operations, a namespace for field definition, a separate namespace describing each implementation of the field protocol (ie. int, string, text, slug, collection).

2) Use a function that returns all the functions used, each implicitly using resources defined by the passed in config, ie.:

(defn make-repository  [config]  (let [db (initialize-db config)        cleanup #(do-cleanup db)        store (fn [key val] (store-data key val db))        retrieve (fn [key] (retrieve-data key db))]    {:db db ;; this is optional, can be very useful during initial development     :cleanup cleanup     :store store     :retrieve retrieve}))

This could of course create an instance of a record if access of the functions is a performance bottleneck, and the record could implement a protocol if you want to define multiple implementations of the same functionality (different db drivers that may need different setup etc.). The user of the library decides how and where to bind these functions you return, as appropriate for their own design.

An example of how a client could use this repository:

(def repo (make-repository config))(def cleanup-repo (:cleanup repo))(def store-to-repo (:store repo))(def retrieve-from-repo (:retrieve repo))(defn store-item  [data]  (let [processed (process data)        key (generate-key data)]    (try (store-to-repo key data)      (catch Exception e         (cleanup-repo)))))

Viewing all articles
Browse latest Browse all 2

Trending Articles