1

I am passing path parameter to fetch data from Database.

End Point

http://localhost:3000/hello/1000

GET Method Code

Code

(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)})))

When I hit the end Point from Postman I get this error,

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

I have come to know the value id is being passed as String value to query.

What is the best way to change Path paramter type to Number before passing to Query?

4

4 回答 4

6

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

[id :<< as-int]

另一种选择是使用 Java 互操作将 id 转换为 Integer:

(Integer/parseInt id)

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

于 2017-07-25T13:51:20.303 回答
2

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

(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))})))
于 2017-07-25T13:52:08.567 回答
1

您似乎正在使用 compojure-api ( https://github.com/metosin/compojure-api ),它支持基于 Schema 和 clojure.spec 的强制。这是使用 Schema 进行路径参数强制的示例: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/

希望这可以帮助。

汤米

于 2017-07-25T20:22:39.777 回答
0

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

(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"))

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

于 2017-07-27T05:10:19.783 回答