Clojure,Compojure:路径参数总是在 Compojure API 中作为字符串传递



我正在传递路径参数以从数据库中获取数据。

终点

http://localhost:3000/hello/1000

获取方法代码

法典

(ns clojure-dauble-business-api.core
(:require [compojure.api.sweet :refer :all]
[ring.util.http-response :refer :all]
[clojure-dauble-business-api.logic :as logic]
[clojure.tools.logging :as log]
[clojure-dauble-business-api.domain.artwork])
(:import [clojure_dauble_business_api.domain.artwork Artwork]))
(defapi app
(GET ["/hello/:id", :id #"[0-9]+"] [id]
(log/info "Function begins from here" id)
(ok {:artwork (logic/artwork-id id)})))

当我从邮递员到达终点时,我收到此错误,

org.postgresql.util.PSQLException: ERROR: operator does not exist: integer = character varying

我已经知道值 id 正在作为字符串值传递给查询。

在传递到查询之前将路径参数类型更改为数字的最佳方法是什么?

使用 Compojure 1.4.0 及更高版本,您可以使用语法强制参数

[id :<< as-int]

另一种选择是使用 Java 互操作将 id 强制转换为整数:

(Integer/parseInt id)

由于您使用的是 compojure-api,因此您还可以使用模式或规范强制输入和输出数据。

我已经找到了解决问题的一种方法,但不确定我是否以正确的方式做?

(defapi app
(GET ["/hello/:id", :id #"[0-9]+"] [id]
(log/info "Function begins from here" id)
(ok {:artwork (logic/artwork-id (->> id (re-find #"d+") Long/parseLong))})))

你似乎正在使用compojure-api(https://github.com/metosin/compojure-api(,它支持Schema和基于clojure.spec的强制。下面是使用架构进行路径参数强制的示例: https://github.com/metosin/compojure-api/blob/master/examples/thingie/src/examples/pizza.clj#L62-L66

有关胁迫的更多详细信息,请点击此处:http://www.metosin.fi/blog/clojure-spec-with-ring-and-swagger/

希望这有帮助。

汤米

我们利用模式的东西来做到这一点。

(context "" []
:middleware [v2-exception-handler]
:header-params [x-user-id :- X-User-Id]

X-User-Id架构在其他地方定义,例如...

(s/defschema X-User-Id
(rss/describe Long "ID of the user to operate on"))

我认为您的验证所做的只是验证字符串的内容是否都是数字。 它不会将其转换为整数。

最新更新