我正在使用 Clojure 中的 Yada 库制作玩具 API。它在数据库中搜索以给定字符开头的城市名称,并返回一些关于它的信息。
我想要一个形式的 URI:/cities/:name?count=:count
所以例如/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}]
{:status 400, :errors ([:query {:error {:count missing-required-key}}])}
但是如果我不提供它,我会得到状态 400 ( ):
$ 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.core/maybe
函数。我试图修改我的 yada 资源如下:
:parameters {:path.....
:query (schema/maybe {:count Long})}
这不起作用(同样的 400 错误)。
然后我尝试了:
:parameters {:path.....
:query {:count (schema/maybe Long)}}
这也没有用。
所以我的问题是:在 yada 中使用可选查询参数的正确方法是什么?