使用compojure-api的可选查询参数(使用默认值)

问题描述 投票:12回答:2

使用compojure-api时,使用默认值声明可选查询参数的正确方法是什么?

我的一个路线元素如下(阅读this后):

(GET "/:id/descendants" [id]
     :return [d/CategoryTreeElement]
     :path-params [id :- Long]
     :query-params [context-type :- d/ContextType
                    levels :- Integer
                    {tenant :- d/Tenant :DEF_TENANT}
                    {show-future :- Boolean false}
                    {show-expired :- Boolean false}
                    {show-suppressed :- Boolean false}
     :summary "Fetch category descendants"
     (ok ...))

首先,布尔参数定义为其他(例如show-future Boolean),但生成的Swagger UI将它们表示为组合框,默认为true值。在当前形式中,UI显示没有选择选项的组合框。租户也是如此。

一方面问题:当我使用Swagger生成的UI发送请求并返回错误时:"levels": "(not (instance? java.lang.Integer \"2\"))"。这是为什么?是不是库应该强制/转换字符串值到API声明的指定类型?

提前致谢。

clojure compojure compojure-api
2个回答
5
投票

对于您的第一个问题,这是按设计工作的。当你需要你的布尔查询参数时,Swagger渲染了UI,迫使你选择一个值(truefalse,只是在第一个地方显示为true)。

当您将布尔查询参数更改为可选时,则第一个空值表示“根本不发送此查询参数”,当您不将其更改为truefalse时,它不会将此查询参数附加到请求。

关于整数查询参数的第二个问题:默认情况下,schema's json-coercion-matcher指定String->Long coercion but not String->Integer,因此不支持开箱即用的Integer。您可以使用:coercion选项(there is an example in compojure-api test)为您的API或每条路线全局指定自己的coercer。您可以提供自己的coercer,可以扩展现有的json-coercion-matcherString->Integer案件。


0
投票

如果您使用clojure.spec并且希望在swagger文档中使用boolean变量作为默认值false,则可以使用spec工具库并执行以下操作:

(s/def ::show-future 
  (st/spec {:spec boolean?
            :example false
            :json-schema/default false}))

然后,在您的查询参数中:

:query-params [{show-future :- ::show-future false}]
© www.soinside.com 2019 - 2024. All rights reserved.