Skip to content

Instantly share code, notes, and snippets.

@kahunamoore
Forked from sgrove/uri_parser.cljs
Last active August 29, 2015 14:22
Show Gist options
  • Save kahunamoore/c3a75098b9e852ad4dc9 to your computer and use it in GitHub Desktop.
Save kahunamoore/c3a75098b9e852ad4dc9 to your computer and use it in GitHub Desktop.
;; Remember to (:import goog.Uri) in your ns declaration
;; Example input/output:
;; http://localhost:10555/?model=duck&manual-tick=false&collapse-all=true&capture-first-frame=true&skybox-name=sky1.png&age=30&money=300.30
;; => {:model "duck",
;; :tick-first-frame? false,
;; :manual-tick? false,
;; :collapse-all? true,
;; :capture-first-frame? true,
;; :skybox-name ["sky1" "png"],
;; :age 30,
;; :money 300.3}
(defn uri-param [parsed-uri param-name & [not-found]]
(let [v (.getParameterValue parsed-uri param-name)]
(cond
(= v "") [(keyword param-name) not-found]
(undefined? v) [(keyword param-name) not-found]
(= v "true") [(keyword (str param-name "?")) true]
(= v "false") [(keyword (str param-name "?")) false]
(= (.toString (js/parseInt v)) v) [(keyword param-name) (js/parseInt v)]
(re-matches #"^\d+\.\d*" v) [(keyword param-name) (js/parseFloat v)]
:else [(keyword param-name) v])))
(def initial-query-map
(let [parsed-uri (goog.Uri. (.. js/window -location -href))
ks (.. parsed-uri getQueryData getKeys)
defaults {:model default-model
:tick-first-frame? false
:manual-tick? false
:collapse-all? false
:capture-first-frame? false}
initial (reduce merge {} (map (partial uri-param parsed-uri) (clj->js ks)))
;; Use this if you need to do any fn-based changes, e.g. split on a uri param
special {:skybox-name (when-let [skybox-name (second (uri-param parsed-uri "skybox-name" "sky1.png"))]
(vec (string/split skybox-name ".")))}]
(merge defaults initial special)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment