forked from loafle/openapi-generator-original
Merge pull request #1659 from xhh/clojure-auth
Improvements on Clojure client: authentications, collectionFormat
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
{{=< >=}}(ns <package>.<classname>
|
||||
(:require [<baseNamespace>.core :refer [call-api check-required-params]])
|
||||
(:require [<baseNamespace>.core :refer [call-api check-required-params with-collection-format]])
|
||||
(:import (java.io File)))
|
||||
<#operations><#operation>
|
||||
(defn <operationId>
|
||||
@@ -9,11 +9,12 @@
|
||||
<#hasOptionalParams>(</hasOptionalParams>[<#allParams><#required><#isFile>^File </isFile><paramName> </required></allParams><#hasOptionalParams>{:keys [<#allParams><^required><#isFile>^File </isFile><paramName> </required></allParams>]}</hasOptionalParams>]<#hasRequiredParams>
|
||||
<#hasOptionalParams> </hasOptionalParams>(check-required-params<#allParams><#required> <paramName></required></allParams>)</hasRequiredParams>
|
||||
<#hasOptionalParams> </hasOptionalParams>(call-api "<path>" :<httpMethod>
|
||||
<#hasOptionalParams> </hasOptionalParams> {:path-params {<#pathParams>"<baseName>" <paramName> </pathParams>}
|
||||
<#hasOptionalParams> </hasOptionalParams> :header-params {<#headerParams>"<baseName>" <paramName> </headerParams>}
|
||||
<#hasOptionalParams> </hasOptionalParams> :query-params {<#queryParams>"<baseName>" <paramName> </queryParams>}
|
||||
<#hasOptionalParams> </hasOptionalParams> :form-params {<#formParams>"<baseName>" <paramName> </formParams>}<#bodyParam>
|
||||
<#hasOptionalParams> </hasOptionalParams> {:path-params {<#pathParams>"<baseName>" <#collectionFormat>(with-collection-format <paramName> :<collectionFormat>)</collectionFormat><^collectionFormat><paramName></collectionFormat> </pathParams>}
|
||||
<#hasOptionalParams> </hasOptionalParams> :header-params {<#headerParams>"<baseName>" <#collectionFormat>(with-collection-format <paramName> :<collectionFormat>)</collectionFormat><^collectionFormat><paramName></collectionFormat> </headerParams>}
|
||||
<#hasOptionalParams> </hasOptionalParams> :query-params {<#queryParams>"<baseName>" <#collectionFormat>(with-collection-format <paramName> :<collectionFormat>)</collectionFormat><^collectionFormat><paramName></collectionFormat> </queryParams>}
|
||||
<#hasOptionalParams> </hasOptionalParams> :form-params {<#formParams>"<baseName>" <#collectionFormat>(with-collection-format <paramName> :<collectionFormat>)</collectionFormat><^collectionFormat><paramName></collectionFormat> </formParams>}<#bodyParam>
|
||||
<#hasOptionalParams> </hasOptionalParams> :body-param <paramName></bodyParam>
|
||||
<#hasOptionalParams> </hasOptionalParams> :content-types [<#consumes>"<mediaType>"<#hasMore> </hasMore></consumes>]
|
||||
<#hasOptionalParams> </hasOptionalParams> :accepts [<#produces>"<mediaType>"<#hasMore> </hasMore></produces>]}))<#hasOptionalParams>)</hasOptionalParams>
|
||||
<#hasOptionalParams> </hasOptionalParams> :accepts [<#produces>"<mediaType>"<#hasMore> </hasMore></produces>]
|
||||
<#hasOptionalParams> </hasOptionalParams> :auth-names [<#authMethods>"<&name>"<#hasMore> </hasMore></authMethods>]})<#hasOptionalParams>)</hasOptionalParams>)
|
||||
</operation></operations>
|
||||
@@ -1,4 +1,4 @@
|
||||
(ns {{{baseNamespace}}}.core
|
||||
{{=< >=}}(ns <&baseNamespace>.core
|
||||
(:require [cheshire.core :refer [generate-string parse-string]]
|
||||
[clojure.string :as str]
|
||||
[clj-http.client :as client])
|
||||
@@ -7,12 +7,18 @@
|
||||
(java.util Date TimeZone)
|
||||
(java.text SimpleDateFormat)))
|
||||
|
||||
(def auth-definitions
|
||||
{<#authMethods>"<&name>" <#isBasic>{:type :basic}</isBasic><#isApiKey>{:type :api-key<#isKeyInHeader> :in :header</isKeyInHeader><#isKeyInQuery> :in :query</isKeyInQuery> :param-name "<&keyParamName>"}</isApiKey><#isOAuth>{:type :oauth2}</isOAuth><#hasMore>
|
||||
</hasMore></authMethods>})
|
||||
|
||||
(def default-api-context
|
||||
"Default API context."
|
||||
{:base-url "http://petstore.swagger.io/v2"
|
||||
{:base-url "<&basePath>"
|
||||
:date-format "yyyy-MM-dd"
|
||||
:datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
|
||||
:debug false})
|
||||
:debug false
|
||||
:auths {<#authMethods>"<&name>" nil<#hasMore>
|
||||
</hasMore></authMethods>}})
|
||||
|
||||
(def ^:dynamic *api-context*
|
||||
"Dynamic API context to be applied in API calls."
|
||||
@@ -20,12 +26,16 @@
|
||||
|
||||
(defmacro with-api-context
|
||||
"A helper macro to wrap *api-context* with default values."
|
||||
[context & body]
|
||||
`(binding [*api-context* (merge *api-context* ~context)]
|
||||
~@body))
|
||||
[api-context & body]
|
||||
`(let [api-context# ~api-context
|
||||
api-context# (-> *api-context*
|
||||
(merge api-context#)
|
||||
(assoc :auths (merge (:auths *api-context*) (:auths api-context#))))]
|
||||
(binding [*api-context* api-context#]
|
||||
~@body)))
|
||||
|
||||
(defmacro check-required-params
|
||||
"Throw exception if the given parameter value is nil."
|
||||
"Throw exception if any of the given parameters is nil."
|
||||
[& params]
|
||||
(->> params
|
||||
(map (fn [p]
|
||||
@@ -33,9 +43,14 @@
|
||||
(throw (IllegalArgumentException. ~(str "The parameter \"" p "\" is required"))))))
|
||||
(list* 'do)))
|
||||
|
||||
(defn- make-date-format
|
||||
([format-str] (make-date-format format-str nil))
|
||||
([format-str time-zone]
|
||||
(defn with-collection-format
|
||||
"Attach collection-format to meta data of the given parameter."
|
||||
[param collection-format]
|
||||
(and param (with-meta param {:collection-format collection-format})))
|
||||
|
||||
(defn- ^SimpleDateFormat make-date-format
|
||||
([^String format-str] (make-date-format format-str nil))
|
||||
([^String format-str ^String time-zone]
|
||||
(let [date-format (SimpleDateFormat. format-str)]
|
||||
(when time-zone
|
||||
(.setTimeZone date-format (TimeZone/getTimeZone time-zone)))
|
||||
@@ -75,35 +90,79 @@
|
||||
(-> (make-date-format datetime-format time-zone)
|
||||
(.parse s)))))
|
||||
|
||||
(defn param-to-str [param]
|
||||
(defn param->str
|
||||
"Format the given parameter value to string."
|
||||
[param]
|
||||
(cond
|
||||
(instance? Date param) (format-datetime param)
|
||||
(sequential? param) (str/join "," param)
|
||||
:else (str param)))
|
||||
|
||||
(defn auth->opts
|
||||
"Process the given auth to an option map that might conatin request options and parameters."
|
||||
[{:keys [type in param-name]} value]
|
||||
(case type
|
||||
:basic {:req-opts {:basic-auth value}}
|
||||
:oauth2 {:req-opts {:oauth-token value}}
|
||||
:api-key (case in
|
||||
:header {:header-params {param-name value}}
|
||||
:query {:query-params {param-name value}}
|
||||
(throw (IllegalArgumentException. (str "Invalid `in` for api-key auth: " in))))
|
||||
(throw (IllegalArgumentException. (str "Invalid auth `type`: " type)))))
|
||||
|
||||
(defn process-auth
|
||||
"Process the given auth name into options, which is merged into the given opts."
|
||||
[opts auth-name]
|
||||
(if-let [value (get-in *api-context* [:auths auth-name])]
|
||||
(merge-with merge
|
||||
opts
|
||||
(auth->opts (get auth-definitions auth-name) value))
|
||||
opts))
|
||||
|
||||
(defn auths->opts
|
||||
"Process the given auth names to an option map that might conatin request options and parameters."
|
||||
[auth-names]
|
||||
(reduce process-auth {} auth-names))
|
||||
|
||||
(declare normalize-param)
|
||||
|
||||
(defn make-url
|
||||
"Make full URL by adding base URL and filling path parameters."
|
||||
[path path-params]
|
||||
(let [path (reduce (fn [p [k v]]
|
||||
(str/replace p (re-pattern (str "\\{" k "\\}")) (param-to-str v)))
|
||||
(str/replace p (re-pattern (str "\\{" k "\\}")) (normalize-param v)))
|
||||
path
|
||||
path-params)]
|
||||
(str (:base-url *api-context*) path)))
|
||||
|
||||
(defn normalize-array-param
|
||||
"Normalize array paramater according to :collection-format specified in the parameter's meta data.
|
||||
When the parameter contains File, a seq is returned so as to keep File parameters.
|
||||
For :multi collection format, a seq is returned which will be handled properly by clj-http.
|
||||
For other cases, a string is returned."
|
||||
[xs]
|
||||
(if (some (partial instance? File) xs)
|
||||
(map normalize-param xs)
|
||||
(case (-> (meta xs) :collection-format (or :csv))
|
||||
:csv (str/join "," (map normalize-param xs))
|
||||
:ssv (str/join " " (map normalize-param xs))
|
||||
:tsv (str/join "\t" (map normalize-param xs))
|
||||
:pipes (str/join "|" (map normalize-param xs))
|
||||
:multi (map normalize-param xs))))
|
||||
|
||||
(defn normalize-param
|
||||
"Normalize parameter value, handling three cases:
|
||||
for sequential value, normalize each elements of it;
|
||||
for File value, do nothing with it;
|
||||
otherwise, call `param-to-string`."
|
||||
for sequential value, apply `normalize-array-param` which handles collection format;
|
||||
for File value, use current value;
|
||||
otherwise, apply `param->str`."
|
||||
[param]
|
||||
(cond
|
||||
(sequential? param) (map normalize-param param)
|
||||
(sequential? param) (normalize-array-param param)
|
||||
(instance? File param) param
|
||||
:else (param-to-str param)))
|
||||
:else (param->str param)))
|
||||
|
||||
(defn normalize-params
|
||||
"Normalize parameters values: remove nils, format to string with `param-to-str`."
|
||||
"Normalize parameters values: remove nils, format to string with `param->str`."
|
||||
[params]
|
||||
(->> params
|
||||
(remove (comp nil? second))
|
||||
@@ -144,7 +203,7 @@
|
||||
;; for non-JSON response, return the body string directly
|
||||
:else body))
|
||||
|
||||
(defn form-params-to-multipart
|
||||
(defn form-params->multipart
|
||||
"Convert the given form parameters map into a vector as clj-http's :multipart option."
|
||||
[form-params]
|
||||
(->> form-params
|
||||
@@ -153,25 +212,27 @@
|
||||
|
||||
(defn call-api
|
||||
"Call an API by making HTTP request and return its response."
|
||||
[path method {:keys [path-params query-params header-params form-params body-param content-types accepts]}]
|
||||
[path method {:keys [path-params body-param content-types accepts auth-names] :as opts}]
|
||||
(let [{:keys [debug]} *api-context*
|
||||
{:keys [req-opts query-params header-params form-params]} (auths->opts auth-names)
|
||||
query-params (merge query-params (:query-params opts))
|
||||
header-params (merge header-params (:header-params opts))
|
||||
form-params (merge form-params (:form-params opts))
|
||||
url (make-url path path-params)
|
||||
content-type (or (json-preferred-mime content-types)
|
||||
(and body-param :json))
|
||||
content-type (or (json-preferred-mime content-types) (and body-param :json))
|
||||
accept (or (json-preferred-mime accepts) :json)
|
||||
multipart? (= "multipart/form-data" content-type)
|
||||
opts (cond-> {:url url :method method}
|
||||
accept (assoc :accept accept)
|
||||
(seq query-params) (assoc :query-params (normalize-params query-params))
|
||||
(seq header-params) (assoc :header-params (normalize-params header-params))
|
||||
(and content-type (not multipart?)) (assoc :content-type content-type)
|
||||
multipart? (assoc :multipart (-> form-params
|
||||
normalize-params
|
||||
form-params-to-multipart))
|
||||
(and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params))
|
||||
body-param (assoc :body (serialize body-param content-type))
|
||||
debug (assoc :debug true :debug-body true))
|
||||
resp (client/request opts)]
|
||||
req-opts (cond-> req-opts
|
||||
true (assoc :url url :method method)
|
||||
accept (assoc :accept accept)
|
||||
(seq query-params) (assoc :query-params (normalize-params query-params))
|
||||
(seq header-params) (assoc :headers (normalize-params header-params))
|
||||
(and content-type (not multipart?)) (assoc :content-type content-type)
|
||||
multipart? (assoc :multipart (-> form-params normalize-params form-params->multipart))
|
||||
(and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params))
|
||||
body-param (assoc :body (serialize body-param content-type))
|
||||
debug (assoc :debug true :debug-body true))
|
||||
resp (client/request req-opts)]
|
||||
(when debug
|
||||
(println "Response:")
|
||||
(println resp))
|
||||
|
||||
Reference in New Issue
Block a user