Guest User

Untitled

a guest
Feb 18th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. (ns user
  2. (:require [clojure.spec.alpha :as s]
  3. [reitit.ring :as ring]
  4. [reitit.coercion.spec]
  5. [muuntaja.core]
  6. [reitit.ring.middleware.exception]
  7. [reitit.ring.middleware.parameters]
  8. [reitit.ring.middleware.muuntaja]
  9. [reitit.ring.coercion]
  10. [spec-tools.core :as st]))
  11.  
  12. ;; a spec-tools transformer
  13. (defn- decode-local-date [_ value]
  14. (try
  15. (if (string? value)
  16. (java.time.LocalDate/parse value))
  17. (catch Exception _
  18. value)))
  19.  
  20. ;; a local-date spec
  21. (s/def ::local-date
  22. (st/spec
  23. {:spec (partial instance? java.time.LocalDate)
  24. :json-schema/type {:type "string", :format "date"}
  25. :decode/string decode-local-date
  26. :decode/json decode-local-date}))
  27.  
  28. ;; application specs
  29. (s/def ::date-str ::local-date)
  30. (s/def ::string-to-date-body (s/keys :req-un [::date-str]))
  31.  
  32. ;; swagger?
  33. (spec-tools.swagger.core/transform ::local-date)
  34. ; {:title "user/local-date", :type {:type "string", :format "date"}}
  35.  
  36. ;; from json
  37. (st/decode (s/keys :req-un [::date-str]) {:date-str "2016-01-01"} st/json-transformer)
  38. ; {:date-str #object[java.time.LocalDate 0x29d996ae "2016-01-01"]}
  39.  
  40. ;; from strings
  41. (st/coerce (s/keys :req-un [::date-str]) {:date-str "2016-01-01"} st/string-transformer)
  42. ; {:date-str #object[java.time.LocalDate 0x29d996ae "2016-01-01"]}
  43.  
  44. ;; the app
  45. (def app
  46. (ring/ring-handler
  47. (ring/router
  48. [["/string-to-date"
  49. {:post {:parameters {:body (s/keys :req-un [::date-str])}
  50. :handler (fn [{{body :body} :parameters}]
  51. (let [coerced-date (:date-str body)]
  52. (if (instance? java.time.LocalDate coerced-date)
  53. {:status 200, :body "its a LocalDate"}
  54. {:status 500, :body (format "coerced type is %s" (type coerced-date))})))}}]]
  55.  
  56. {:data {:coercion reitit.coercion.spec/coercion
  57. :muuntaja muuntaja.core/instance
  58. :middleware [reitit.ring.middleware.exception/exception-middleware
  59. reitit.ring.middleware.parameters/parameters-middleware
  60. reitit.ring.middleware.muuntaja/format-negotiate-middleware
  61. reitit.ring.middleware.muuntaja/format-response-middleware
  62. reitit.ring.middleware.muuntaja/format-request-middleware
  63. reitit.ring.coercion/coerce-response-middleware
  64. reitit.ring.coercion/coerce-request-middleware]}})))
  65.  
  66. ;; testing
  67. (app {:request-method :post,
  68. :headers {"content-type" "application/json"}
  69. :uri "/string-to-date",
  70. :body (muuntaja.core/encode "application/json" {:date-str "2016-01-01"})})
  71. ;; {:status 200, :body "its a LocalDate"}
Add Comment
Please, Sign In to add comment