parent
d56f20dab3
commit
c7ef20f09b
@ -0,0 +1,49 @@
|
||||
(ns wanijo.framework.routing
|
||||
(:require [clojure.string :as string]))
|
||||
|
||||
(def all-routes
|
||||
(atom {}))
|
||||
|
||||
(defn register [id path]
|
||||
(swap! all-routes
|
||||
assoc id path))
|
||||
|
||||
(defn check-params [id path params]
|
||||
(when (nil? path)
|
||||
(throw
|
||||
(ex-info
|
||||
(str "Path " id " is not registered")
|
||||
{:id id
|
||||
:params params})))
|
||||
(let [matcher (re-matcher #":[^/]+" path)
|
||||
matches (take-while some? (repeatedly #(re-find matcher)))]
|
||||
(doseq [match matches
|
||||
:let [kwparam (keyword (subs match 1))
|
||||
exists? (contains? params kwparam)]]
|
||||
(when-not exists?
|
||||
(throw
|
||||
(ex-info
|
||||
(str "Key '" kwparam
|
||||
"' does not exist in parameter map for path "
|
||||
path)
|
||||
{:path path
|
||||
:params params
|
||||
:id id}))))))
|
||||
|
||||
(defn path
|
||||
([id]
|
||||
(path id {}))
|
||||
([id params]
|
||||
(let [path (id @all-routes)]
|
||||
(check-params id path params)
|
||||
(reduce-kv
|
||||
(fn [new-path param-id param-value]
|
||||
(string/replace
|
||||
new-path
|
||||
(str ":" (name param-id))
|
||||
param-value))
|
||||
path
|
||||
params))))
|
||||
|
||||
(defn raw-path [id]
|
||||
(id @all-routes))
|
@ -1,6 +1,9 @@
|
||||
(ns wanijo.home.routes
|
||||
(:require [compojure.core :refer [defroutes GET]]
|
||||
[wanijo.framework.routing :refer [register]]
|
||||
[wanijo.home.view :as home-view]))
|
||||
|
||||
(register :home "/")
|
||||
|
||||
(defroutes routes
|
||||
(GET "/" [] home-view/root!))
|
||||
|
Loading…
Reference in new issue