-
Notifications
You must be signed in to change notification settings - Fork 250
/
multipart.clj
64 lines (57 loc) · 2.52 KB
/
multipart.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
(ns reitit.http.interceptors.multipart
(:require [clojure.spec.alpha :as s]
[reitit.coercion :as coercion]
[reitit.spec]
[ring.middleware.multipart-params :as multipart-params]
[spec-tools.core :as st])
(:import (java.io File)))
(s/def ::filename string?)
(s/def ::content-type string?)
(s/def ::tempfile (partial instance? File))
(s/def ::bytes bytes?)
(s/def ::size int?)
(s/def ::multipart :reitit.core.coercion/model)
(s/def ::parameters (s/keys :opt-un [::multipart]))
(def temp-file-part
"Spec for file param created by ring.middleware.multipart-params.temp-file store."
(st/spec
{:spec (s/keys :req-un [::filename ::content-type ::tempfile ::size])
:swagger {:type "file"}
:openapi {:type "string"
:format "binary"}}))
(def bytes-part
"Spec for file param created by ring.middleware.multipart-params.byte-array store."
(st/spec
{:spec (s/keys :req-un [::filename ::content-type ::bytes])
:swagger {:type "file"}
:openapi {:type "string"
:format "binary"}}))
(defn- coerced-request [request coercers]
(if-let [coerced (if coercers (coercion/coerce-request coercers request))]
(update request :parameters merge coerced)
request))
;;
;; public api
;;
(defn multipart-interceptor
"Creates a Interceptor to handle the multipart params, based on
ring.middleware.multipart-params, taking same options. Mounts only
if endpoint has `[:parameters :multipart]` defined. Publishes coerced
parameters into `[:parameters :multipart]` under request."
([]
(multipart-interceptor nil))
([options]
{:name ::multipart
:spec ::parameters
:compile (fn [{:keys [parameters coercion]} opts]
(if-let [multipart (:multipart parameters)]
(let [parameter-coercion {:multipart (coercion/->ParameterCoercion
:multipart-params :string true true)}
opts (assoc opts ::coercion/parameter-coercion parameter-coercion)
coercers (if multipart (coercion/request-coercers coercion parameters opts))]
{:data {:swagger {:consumes ^:replace #{"multipart/form-data"}}}
:enter (fn [ctx]
(let [request (-> (:request ctx)
(multipart-params/multipart-params-request options)
(coerced-request coercers))]
(assoc ctx :request request)))})))}))