【问题标题】:How to use optional query parameters in Yada?雅达如何使用可选查询参数?
【发布时间】:2019-09-10 00:55:40
【问题描述】:

我正在使用 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.core/maybe 函数。我尝试修改我的 yada 资源如下:

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

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

然后我尝试了:

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

这也没有用。

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

【问题讨论】:

    标签: clojure yada


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2010-09-10
      • 2019-03-22
      • 2016-09-08
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      相关资源
      最近更新 更多