如何在Yada中使用可选的查询参数?

时间:2019-09-09 16:09:49

标签: clojure yada

我正在使用Clojure中的Yada库制作玩具API。它会在数据库中搜索以给定字符开头的城市名称,并返回有关该城市的信息。

我想要一个格式为/cities/:name?count=:count的URI,因此例如/cities/ber?count=4将返回前4个匹配项。但是我也希望没有/cities/ber参数的?count=返回默认数量的结果(比如说第一个)。

我已经这样定义了路线和yada处理程序:

(defn city-search-fn
  [ctx]
  (let [name (get-in ctx [:parameters :path :name])
        count (get-in ctx [:parameters :query :count] 1)]
    (city->geoposition name count)))

(def cities (yada/handler (yada/resource 
                            {:methods 
                             {:get
                              {:parameters {:path {:name String}
                                            :query {:count Long}}
                               :produces ["application/json"
                                          "application/edn"]
                               :response city-search-fn}}})))

(def routes
  [["/cities/" :name] cities])

(def server
  (yada/listener routes {:port 30000}))

如果我提供?count=查询参数,此方法就很好:

$ curl -i 'http://localhost:30000/cities/ber?count=2'
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Length: 259
Content-Type: application/json
Vary: accept
Server: Aleph/0.4.4
Connection: Keep-Alive
Date: Mon, 09 Sep 2019 16:01:45 GMT

[{"name":"Berlin","state":"Berlin","countrycode":"DE","timezone":"Europe/Berlin","latitude":52.52437,"longitude":13.41053},{"name":"Berbera","state":"Woqooyi Galbeed","countrycode":"SO","timezone":"Africa/Mogadishu","latitude":10.43959,"longitude":45.01432}]

但是如果我不提供状态为400({:status 400, :errors ([:query {:error {:count missing-required-key}}])}

$ curl -i 'http://localhost:30000/cities/ber'
HTTP/1.1 400 Bad Request
Content-Length: 77
Content-Type: text/plain;charset=utf-8
Server: Aleph/0.4.4
Connection: Keep-Alive
Date: Mon, 09 Sep 2019 16:06:56 GMT



{:status 400, :errors ([:query {:error {:count missing-required-key}}])}

yada的文档说它使用“ schema”库支持可选的查询参数。因此,我在架构的文档中发现了一个schema.core/maybe函数。我试图按如下方式修改我的yada资源:

:parameters {:path.....
             :query (schema/maybe {:count Long})}

这不起作用(相同的400错误)。

然后我尝试:

:parameters {:path.....
             :query {:count  (schema/maybe Long)}}

这也不起作用。

所以我的问题是:在yada中具有可选查询参数的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

要回答我自己的问题,请深入研究Schema文档,这是正确的方法:

:parameters {:path.....
             :query {(schema/optional-key :count) Long}}

密钥本身需要标记为可选。