update clojure default value (#377)

This commit is contained in:
William Cheng 2018-05-09 10:30:35 +08:00 committed by GitHub
parent 9ecd3586b5
commit ded082202e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 14 additions and 668 deletions

View File

@ -1,10 +1,10 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId>
<artifactId>swagger-petstore-clojure</artifactId>
<groupId>org.openapitools</groupId>
<artifactId>openapi-petstore-clojure</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>Swagger Petstore - Clojure Client</name>
<name>OpenAPI Clogure Petstore Client</name>
<build>
<plugins>
<plugin>

View File

@ -1,166 +0,0 @@
(ns swagger-petstore.api.pet
(:require [swagger-petstore.core :refer [call-api check-required-params with-collection-format]])
(:import (java.io File)))
(defn add-pet-with-http-info
"Add a new pet to the store"
([] (add-pet-with-http-info nil))
([{:keys [pet ]}]
(call-api "/pet" :post
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:body-param pet
:content-types []
:accepts []
:auth-names ["petstore_auth"]})))
(defn add-pet
"Add a new pet to the store"
([] (add-pet nil))
([optional-params]
(:data (add-pet-with-http-info optional-params))))
(defn delete-pet-with-http-info
"Deletes a pet"
([pet-id ] (delete-pet-with-http-info pet-id nil))
([pet-id {:keys [api-key ]}]
(check-required-params pet-id)
(call-api "/pet/{petId}" :delete
{:path-params {"petId" pet-id }
:header-params {"api_key" api-key }
:query-params {}
:form-params {}
:content-types []
:accepts []
:auth-names ["petstore_auth"]})))
(defn delete-pet
"Deletes a pet"
([pet-id ] (delete-pet pet-id nil))
([pet-id optional-params]
(:data (delete-pet-with-http-info pet-id optional-params))))
(defn find-pets-by-status-with-http-info
"Finds Pets by status
Multiple status values can be provided with comma separated strings"
([] (find-pets-by-status-with-http-info nil))
([{:keys [status ]}]
(call-api "/pet/findByStatus" :get
{:path-params {}
:header-params {}
:query-params {"status" (with-collection-format status :multi) }
:form-params {}
:content-types []
:accepts ["application/json" "application/xml"]
:auth-names ["petstore_auth"]})))
(defn find-pets-by-status
"Finds Pets by status
Multiple status values can be provided with comma separated strings"
([] (find-pets-by-status nil))
([optional-params]
(:data (find-pets-by-status-with-http-info optional-params))))
(defn find-pets-by-tags-with-http-info
"Finds Pets by tags
Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing."
([] (find-pets-by-tags-with-http-info nil))
([{:keys [tags ]}]
(call-api "/pet/findByTags" :get
{:path-params {}
:header-params {}
:query-params {"tags" (with-collection-format tags :multi) }
:form-params {}
:content-types []
:accepts ["application/json" "application/xml"]
:auth-names ["petstore_auth"]})))
(defn find-pets-by-tags
"Finds Pets by tags
Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing."
([] (find-pets-by-tags nil))
([optional-params]
(:data (find-pets-by-tags-with-http-info optional-params))))
(defn get-pet-by-id-with-http-info
"Find pet by ID
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions"
[pet-id ]
(check-required-params pet-id)
(call-api "/pet/{petId}" :get
{:path-params {"petId" pet-id }
:header-params {}
:query-params {}
:form-params {}
:content-types []
:accepts ["application/json" "application/xml"]
:auth-names ["api_key" "petstore_auth"]}))
(defn get-pet-by-id
"Find pet by ID
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions"
[pet-id ]
(:data (get-pet-by-id-with-http-info pet-id)))
(defn update-pet-with-http-info
"Update an existing pet"
([] (update-pet-with-http-info nil))
([{:keys [pet ]}]
(call-api "/pet" :put
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:body-param pet
:content-types []
:accepts []
:auth-names ["petstore_auth"]})))
(defn update-pet
"Update an existing pet"
([] (update-pet nil))
([optional-params]
(:data (update-pet-with-http-info optional-params))))
(defn update-pet-with-form-with-http-info
"Updates a pet in the store with form data"
([pet-id ] (update-pet-with-form-with-http-info pet-id nil))
([pet-id {:keys [name status ]}]
(check-required-params pet-id)
(call-api "/pet/{petId}" :post
{:path-params {"petId" pet-id }
:header-params {}
:query-params {}
:form-params {"name" name "status" status }
:content-types ["application/x-www-form-urlencoded"]
:accepts []
:auth-names ["petstore_auth"]})))
(defn update-pet-with-form
"Updates a pet in the store with form data"
([pet-id ] (update-pet-with-form pet-id nil))
([pet-id optional-params]
(:data (update-pet-with-form-with-http-info pet-id optional-params))))
(defn upload-file-with-http-info
"uploads an image"
([pet-id ] (upload-file-with-http-info pet-id nil))
([pet-id {:keys [additional-metadata ^File file ]}]
(check-required-params pet-id)
(call-api "/pet/{petId}/uploadImage" :post
{:path-params {"petId" pet-id }
:header-params {}
:query-params {}
:form-params {"additionalMetadata" additional-metadata "file" file }
:content-types ["multipart/form-data"]
:accepts []
:auth-names ["petstore_auth"]})))
(defn upload-file
"uploads an image"
([pet-id ] (upload-file pet-id nil))
([pet-id optional-params]
(:data (upload-file-with-http-info pet-id optional-params))))

View File

@ -1,83 +0,0 @@
(ns swagger-petstore.api.store
(:require [swagger-petstore.core :refer [call-api check-required-params with-collection-format]])
(:import (java.io File)))
(defn delete-order-with-http-info
"Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors"
[order-id ]
(check-required-params order-id)
(call-api "/store/order/{orderId}" :delete
{:path-params {"orderId" order-id }
:header-params {}
:query-params {}
:form-params {}
:content-types []
:accepts []
:auth-names []}))
(defn delete-order
"Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors"
[order-id ]
(:data (delete-order-with-http-info order-id)))
(defn get-inventory-with-http-info
"Returns pet inventories by status
Returns a map of status codes to quantities"
[]
(call-api "/store/inventory" :get
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:content-types []
:accepts ["application/json" "application/xml"]
:auth-names ["api_key"]}))
(defn get-inventory
"Returns pet inventories by status
Returns a map of status codes to quantities"
[]
(:data (get-inventory-with-http-info)))
(defn get-order-by-id-with-http-info
"Find purchase order by ID
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions"
[order-id ]
(check-required-params order-id)
(call-api "/store/order/{orderId}" :get
{:path-params {"orderId" order-id }
:header-params {}
:query-params {}
:form-params {}
:content-types []
:accepts ["application/json" "application/xml"]
:auth-names []}))
(defn get-order-by-id
"Find purchase order by ID
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions"
[order-id ]
(:data (get-order-by-id-with-http-info order-id)))
(defn place-order-with-http-info
"Place an order for a pet"
([] (place-order-with-http-info nil))
([{:keys [order ]}]
(call-api "/store/order" :post
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:body-param order
:content-types ["application/json"]
:accepts ["application/json" "application/xml"]
:auth-names []})))
(defn place-order
"Place an order for a pet"
([] (place-order nil))
([optional-params]
(:data (place-order-with-http-info optional-params))))

View File

@ -1,163 +0,0 @@
(ns swagger-petstore.api.user
(:require [swagger-petstore.core :refer [call-api check-required-params with-collection-format]])
(:import (java.io File)))
(defn create-user-with-http-info
"Create user
This can only be done by the logged in user."
([] (create-user-with-http-info nil))
([{:keys [user ]}]
(call-api "/user" :post
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:body-param user
:content-types ["application/json"]
:accepts []
:auth-names []})))
(defn create-user
"Create user
This can only be done by the logged in user."
([] (create-user nil))
([optional-params]
(:data (create-user-with-http-info optional-params))))
(defn create-users-with-array-input-with-http-info
"Creates list of users with given input array"
([] (create-users-with-array-input-with-http-info nil))
([{:keys [user ]}]
(call-api "/user/createWithArray" :post
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:body-param user
:content-types []
:accepts []
:auth-names []})))
(defn create-users-with-array-input
"Creates list of users with given input array"
([] (create-users-with-array-input nil))
([optional-params]
(:data (create-users-with-array-input-with-http-info optional-params))))
(defn create-users-with-list-input-with-http-info
"Creates list of users with given input array"
([] (create-users-with-list-input-with-http-info nil))
([{:keys [user ]}]
(call-api "/user/createWithList" :post
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:body-param user
:content-types []
:accepts []
:auth-names []})))
(defn create-users-with-list-input
"Creates list of users with given input array"
([] (create-users-with-list-input nil))
([optional-params]
(:data (create-users-with-list-input-with-http-info optional-params))))
(defn delete-user-with-http-info
"Delete user
This can only be done by the logged in user."
[username ]
(check-required-params username)
(call-api "/user/{username}" :delete
{:path-params {"username" username }
:header-params {}
:query-params {}
:form-params {}
:content-types []
:accepts []
:auth-names []}))
(defn delete-user
"Delete user
This can only be done by the logged in user."
[username ]
(:data (delete-user-with-http-info username)))
(defn get-user-by-name-with-http-info
"Get user by user name"
[username ]
(check-required-params username)
(call-api "/user/{username}" :get
{:path-params {"username" username }
:header-params {}
:query-params {}
:form-params {}
:content-types []
:accepts ["application/json" "application/xml"]
:auth-names []}))
(defn get-user-by-name
"Get user by user name"
[username ]
(:data (get-user-by-name-with-http-info username)))
(defn login-user-with-http-info
"Logs user into the system"
([] (login-user-with-http-info nil))
([{:keys [username password ]}]
(call-api "/user/login" :get
{:path-params {}
:header-params {}
:query-params {"username" username "password" password }
:form-params {}
:content-types []
:accepts ["application/json" "application/xml"]
:auth-names []})))
(defn login-user
"Logs user into the system"
([] (login-user nil))
([optional-params]
(:data (login-user-with-http-info optional-params))))
(defn logout-user-with-http-info
"Logs out current logged in user session"
[]
(call-api "/user/logout" :get
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:content-types []
:accepts []
:auth-names []}))
(defn logout-user
"Logs out current logged in user session"
[]
(:data (logout-user-with-http-info)))
(defn update-user-with-http-info
"Updated user
This can only be done by the logged in user."
([username ] (update-user-with-http-info username nil))
([username {:keys [user ]}]
(check-required-params username)
(call-api "/user/{username}" :put
{:path-params {"username" username }
:header-params {}
:query-params {}
:form-params {}
:body-param user
:content-types ["application/json"]
:accepts []
:auth-names []})))
(defn update-user
"Updated user
This can only be done by the logged in user."
([username ] (update-user username nil))
([username optional-params]
(:data (update-user-with-http-info username optional-params))))

View File

@ -1,242 +0,0 @@
(ns swagger-petstore.core
(:require [cheshire.core :refer [generate-string parse-string]]
[clojure.string :as str]
[clj-http.client :as client])
(:import (com.fasterxml.jackson.core JsonParseException)
(java.io File)
(java.util Date TimeZone)
(java.text SimpleDateFormat)))
(def auth-definitions
{"api_key" {:type :api-key :in :header :param-name "api_key"}
"petstore_auth" {:type :oauth2}})
(def default-api-context
"Default API context."
{:base-url "http://petstore.swagger.io/v2"
:date-format "yyyy-MM-dd"
:datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
:debug false
:auths {"api_key" nil
"petstore_auth" nil}})
(def ^:dynamic *api-context*
"Dynamic API context to be applied in API calls."
default-api-context)
(defmacro with-api-context
"A helper macro to wrap *api-context* with default values."
[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 any of the given parameters is nil."
[& params]
(->> params
(map (fn [p]
`(if (nil? ~p)
(throw (IllegalArgumentException. ~(str "The parameter \"" p "\" is required"))))))
(list* 'do)))
(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)))
date-format)))
(defn format-date
"Format the given Date object with the :date-format defined in *api-options*.
NOTE: The UTC time zone is used."
[^Date date]
(let [{:keys [date-format]} *api-context*]
(-> (make-date-format date-format "UTC")
(.format date))))
(defn parse-date
"Parse the given string to a Date object with the :date-format defined in *api-options*.
NOTE: The UTC time zone is used."
[^String s]
(let [{:keys [date-format]} *api-context*]
(-> (make-date-format date-format "UTC")
(.parse s))))
(defn format-datetime
"Format the given Date object with the :datetime-format defined in *api-options*.
NOTE: The system's default time zone is used when not provided."
([^Date date] (format-datetime date nil))
([^Date date ^String time-zone]
(let [{:keys [datetime-format]} *api-context*]
(-> (make-date-format datetime-format time-zone)
(.format date)))))
(defn parse-datetime
"Parse the given string to a Date object with the :datetime-format defined in *api-options*.
NOTE: The system's default time zone is used when not provided."
([^String s] (parse-datetime s nil))
([^String s ^String time-zone]
(let [{:keys [datetime-format]} *api-context*]
(-> (make-date-format datetime-format time-zone)
(.parse s)))))
(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 "\\}")) (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, apply `normalize-array-param` which handles collection format;
for File value, use current value;
otherwise, apply `param->str`."
[param]
(cond
(sequential? param) (normalize-array-param param)
(instance? File param) param
:else (param->str param)))
(defn normalize-params
"Normalize parameters values: remove nils, format to string with `param->str`."
[params]
(->> params
(remove (comp nil? second))
(map (fn [[k v]] [k (normalize-param v)]))
(into {})))
(defn json-mime?
"Check if the given MIME is a standard JSON MIME or :json."
[mime]
(if mime
(or (= :json mime)
(re-matches #"(?i)application/json(;.*)?" (name mime)))))
(defn json-preferred-mime
"Choose a MIME from the given MIMEs with JSON preferred,
i.e. return JSON if included, otherwise return the first one."
[mimes]
(-> (filter json-mime? mimes)
first
(or (first mimes))))
(defn serialize
"Serialize the given data according to content-type.
Only JSON is supported for now."
[data content-type]
(if (json-mime? content-type)
(generate-string data {:date-format (:datetime-format *api-context*)})
(throw (IllegalArgumentException. (str "Content type \"" content-type "\" is not support for serialization")))))
(defn deserialize
"Deserialize the given HTTP response according to the Content-Type header."
[{:keys [body] {:keys [content-type]} :headers}]
(cond
(json-mime? content-type)
(try
(parse-string body true)
(catch JsonParseException e
;; Return the body string directly on JSON parsing error.
body))
;; For other cases, return the body string directly.
:else body))
(defn form-params->multipart
"Convert the given form parameters map into a vector as clj-http's :multipart option."
[form-params]
(->> form-params
(map (fn [[k v]] (array-map :name k :content v)))
vec))
(defn call-api
"Call an API by making HTTP request and return its response."
[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))
accept (or (json-preferred-mime accepts) :json)
multipart? (= "multipart/form-data" content-type)
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))
(assoc resp :data (deserialize resp))))

View File

@ -1,8 +1,8 @@
(ns swagger-petstore.api.pet-test
(ns open-api-petstore.api.pet-test
(:require [clojure.test :refer :all]
[clojure.java.io :as io]
[swagger-petstore.core :refer [with-api-context]]
[swagger-petstore.api.pet :refer :all]))
[open-api-petstore.core :refer [with-api-context]]
[open-api-petstore.api.pet :refer :all]))
(defn credentials-fixture [f]
(with-api-context {:auths {"api_key" "special-key"}}

View File

@ -1,7 +1,7 @@
(ns swagger-petstore.api.store-test
(ns open-api-petstore.api.store-test
(:require [clojure.test :refer :all]
[swagger-petstore.core :refer [with-api-context]]
[swagger-petstore.api.store :refer :all])
[open-api-petstore.core :refer [with-api-context]]
[open-api-petstore.api.store :refer :all])
(:import (java.util Date)))
(defn credentials-fixture [f]

View File

@ -1,7 +1,7 @@
(ns swagger-petstore.api.user-test
(ns open-api-petstore.api.user-test
(:require [clojure.test :refer :all]
[swagger-petstore.core :refer [with-api-context]]
[swagger-petstore.api.user :refer :all]))
[open-api-petstore.core :refer [with-api-context]]
[open-api-petstore.api.user :refer :all]))
(defn credentials-fixture [f]
(with-api-context {:auths {"api_key" "special-key"}}

View File

@ -1,7 +1,7 @@
(ns swagger-petstore.core-test
(ns open-api-petstore.core-test
(:require [clojure.java.io :as io]
[clojure.test :refer :all]
[swagger-petstore.core :refer :all])
[open-api-petstore.core :refer :all])
(:import (java.text ParseException)))
(deftest test-api-context