[英]ClojureScript - construct url conditionally in go block
I am using cemerick/url to construct my URL for an ajax request. 我正在使用cemerick / url为ajax请求构造URL。 However, some of the parameters of the query are coming from an asynchronous native callback. 但是,查询的某些参数来自异步本机回调。 So I put everything in a go
block, like the following : 因此,我将所有内容放入go
块中,如下所示:
(defn myFn [options]
(go (let [options (cond-> options
;; the asynchronous call
(= (:loc options) "getgeo") (assoc :loc (aget (<! (!geolocation)) "coords")))
constructing the url
url (-> "http://example.com"
(assoc-in [:query :param] "a param")
;; How do I not associate those if they don't exist ?
;; I tried something along the lines of this, but it obviously doesn't work.
;; (cond-> (and
;; (-> options :loc :latitude not-nil?)
;; (-> options :loc :latitude not-nil?))
;; (do
;; ))
;; these will fail if there is no "latitude" or "longitude" in options
(assoc-in [:query :lat] (aget (:loc options) "latitude"))
(assoc-in [:query :lng] (aget (:loc options) "longitude"))
;; url function from https://github.com/cemerick/url
(url "/subscribe")
str)])))
I would like to be able to be able to pass either {:loc "local}
or {:loc {:latitude 12 :longitude 34}}
or {}
as a parameter to my function. I feel that I am not using the right structure already. 我希望能够将{:loc "local}
或{:loc {:latitude 12 :longitude 34}}
或{}
作为参数传递给我的函数,我觉得我没有使用正确的结构已经。
How I should construct this url ? 我应该如何构造该URL?
If I understood your question right, you require code, which looks like that: 如果我正确理解了您的问题,则需要使用如下代码:
;; helper function
(defn add-loc-to-url-as [url loc k as-k]
(if-let [v (k loc)]
(assoc-in url [:query as-k] v)
url))
;; define function, that process options and extends URL
(defn add-location [url options]
(if-let [location (:loc options)]
(if (string? location)
;;; it expects string, for {:loc "San Francisco"}
(assoc-in url [:query :location] location)
;;; or map, for {:loc {:latitude 12.123, :longitude 34.33}}
(-> url
(add-loc-to-url-as location :latitude :lat)
(add-loc-to-url-as location :longitude :lng)))
url))
;; now you can use it in your block
;; ...
the-url (-> (url "http://example.com" "subscribe")
(assoc-in [:query :param] "a param")
(add-location options))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.