我正在使用Clojure中的Yada库制作一个玩具API。它在数据库中搜索以给定字符开头的城市名称,并返回有关该城市的一些信息。
我需要一个形式为:/cities/:name?count=:count的URI,例如,/cities/ber?count=4将返回前4个匹配项。但我也希望不带?count=参数的/cities/ber返回默认数量的结果(比如只返回第一个)。
我已经像这样定义了我的路由和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中使用可选查询参数的正确方法是什么?
发布于 2019-09-10 00:55:40
为了回答我自己的问题,深入研究Schema文档,下面是正确的方法:
:parameters {:path.....
:query {(schema/optional-key :count) Long}}密钥本身需要标记为可选。
https://stackoverflow.com/questions/57857614
复制相似问题