From 487146c266b9014777977b3d69ee76522e90c5f9 Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Sat, 5 Aug 2017 09:49:07 -0500 Subject: [PATCH 1/6] Go -> Rust in README --- modules/swagger-codegen/src/main/resources/rust/README.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/README.mustache b/modules/swagger-codegen/src/main/resources/rust/README.mustache index 0e89ca61846..67cc0280e2c 100644 --- a/modules/swagger-codegen/src/main/resources/rust/README.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/README.mustache @@ -1,4 +1,4 @@ -# Go API client for {{packageName}} +# Rust API client for {{packageName}} {{#appDescription}} {{{appDescription}}} From 7da4e341fe71bf4bb84b3a35224a16985257500b Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Sat, 5 Aug 2017 09:49:25 -0500 Subject: [PATCH 2/6] Remove leftover go file in rust sample --- .../petstore/rust/src/apis/api_client.rs | 423 ------------------ 1 file changed, 423 deletions(-) delete mode 100644 samples/client/petstore/rust/src/apis/api_client.rs diff --git a/samples/client/petstore/rust/src/apis/api_client.rs b/samples/client/petstore/rust/src/apis/api_client.rs deleted file mode 100644 index f629d8b8910..00000000000 --- a/samples/client/petstore/rust/src/apis/api_client.rs +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Swagger Petstore - * - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package swagger - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "errors" - "io" - "mime/multipart" - "golang.org/x/oauth2" - "golang.org/x/net/context" - "net/http" - "net/url" - "time" - "os" - "path/filepath" - "reflect" - "regexp" - "strings" - "unicode/utf8" - "strconv" -) - -var ( - jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") - xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") -) - -/// APIClient manages communication with the Swagger Petstore API v1.0.0 -/// In most cases there should be only one, shared, APIClient. -type APIClient struct { - cfg *Configuration - common service /// Reuse a single struct instead of allocating one for each service on the heap. - - /// API Services - PetApi *PetApiService - StoreApi *StoreApiService - UserApi *UserApiService -} - -type service struct { - client *APIClient -} - -/// NewAPIClient creates a new API client. Requires a userAgent string describing your application. -/// optionally a custom http.Client to allow for advanced features such as caching. -func NewAPIClient(cfg *Configuration) *APIClient { - if cfg.HTTPClient == nil { - cfg.HTTPClient = http.DefaultClient - } - - c := &APIClient{} - c.cfg = cfg - c.common.client = c - - /// API Services - c.PetApi = (*PetApiService)(&c.common) - c.StoreApi = (*StoreApiService)(&c.common) - c.UserApi = (*UserApiService)(&c.common) - - return c -} - -func atoi(in string) (int, error) { - return strconv.Atoi(in) -} - - -/// selectHeaderContentType select a content type from the available list. -func selectHeaderContentType(contentTypes []string) string { - if len(contentTypes) == 0 { - return "" - } - if contains(contentTypes, "application/json") { - return "application/json" - } - return contentTypes[0] /// use the first content type specified in 'consumes' -} - -/// selectHeaderAccept join all accept types and return -func selectHeaderAccept(accepts []string) string { - if len(accepts) == 0 { - return "" - } - - if contains(accepts, "application/json") { - return "application/json" - } - - return strings.Join(accepts, ",") -} - -/// contains is a case insenstive match, finding needle in a haystack -func contains(haystack []string, needle string) bool { - for _, a := range haystack { - if strings.ToLower(a) == strings.ToLower(needle) { - return true - } - } - return false -} - -/// Verify optional parameters are of the correct type. -func typeCheckParameter(obj interface{}, expected string, name string) error { - /// Make sure there is an object. - if obj == nil { - return nil - } - - /// Check the type is as expected. - if reflect.TypeOf(obj).String() != expected { - return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) - } - return nil -} - -/// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. -func parameterToString(obj interface{}, collectionFormat string) string { - var delimiter string - - switch collectionFormat { - case "pipes": - delimiter = "|" - case "ssv": - delimiter = " " - case "tsv": - delimiter = "\t" - case "csv": - delimiter = "," - } - - if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") - } - - return fmt.Sprintf("%v", obj) -} - -/// callAPI do the request. -func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { - return c.cfg.HTTPClient.Do(request) -} - -/// Change base path to allow switching to mocks -func (c *APIClient) ChangeBasePath (path string) { - c.cfg.BasePath = path -} - -/// prepareRequest build the request -func (c *APIClient) prepareRequest ( - ctx context.Context, - path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams url.Values, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { - - var body *bytes.Buffer - - /// Detect postBody type and post. - if postBody != nil { - contentType := headerParams["Content-Type"] - if contentType == "" { - contentType = detectContentType(postBody) - headerParams["Content-Type"] = contentType - } - - body, err = setBody(postBody, contentType) - if err != nil { - return nil, err - } - } - - /// add form paramters and file if available. - if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { - if body != nil { - return nil, errors.New("Cannot specify postBody and multipart form at the same time.") - } - body = &bytes.Buffer{} - w := multipart.NewWriter(body) - - for k, v := range formParams { - for _, iv := range v { - if strings.HasPrefix(k, "@") { /// file - err = addFile(w, k[1:], iv) - if err != nil { - return nil, err - } - } else { /// form value - w.WriteField(k, iv) - } - } - } - if len(fileBytes) > 0 && fileName != "" { - w.Boundary() - ///_, fileNm := filepath.Split(fileName) - part, err := w.CreateFormFile("file", filepath.Base(fileName)) - if err != nil { - return nil, err - } - _, err = part.Write(fileBytes) - if err != nil { - return nil, err - } - /// Set the Boundary in the Content-Type - headerParams["Content-Type"] = w.FormDataContentType() - } - - /// Set Content-Length - headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) - w.Close() - } - - /// Setup path and query paramters - url, err := url.Parse(path) - if err != nil { - return nil, err - } - - /// Adding Query Param - query := url.Query() - for k, v := range queryParams { - for _, iv := range v { - query.Add(k, iv) - } - } - - /// Encode the parameters. - url.RawQuery = query.Encode() - - /// Generate a new request - if body != nil { - localVarRequest, err = http.NewRequest(method, url.String(), body) - } else { - localVarRequest, err = http.NewRequest(method, url.String(), nil) - } - if err != nil { - return nil, err - } - - /// add header parameters, if any - if len(headerParams) > 0 { - headers := http.Header{} - for h, v := range headerParams { - headers.Set(h, v) - } - localVarRequest.Header = headers - } - - /// Add the user agent to the request. - localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) - - /// Walk through any authentication. - if ctx != nil { - /// OAuth2 authentication - if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { - /// We were able to grab an oauth2 token from the context - var latestToken *oauth2.Token - if latestToken, err = tok.Token(); err != nil { - return nil, err - } - - latestToken.SetAuthHeader(localVarRequest) - } - - /// Basic HTTP Authentication - if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { - localVarRequest.SetBasicAuth(auth.UserName, auth.Password) - } - - /// AccessToken Authentication - if auth, ok := ctx.Value(ContextAccessToken).(string); ok { - localVarRequest.Header.Add("Authorization", "Bearer " + auth) - } - } - - for header, value := range c.cfg.DefaultHeader { - localVarRequest.Header.Add(header, value) - } - - return localVarRequest, nil -} - - -/// Add a file to the multipart request -func addFile(w *multipart.Writer, fieldName, path string) error { - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - - part, err := w.CreateFormFile(fieldName, filepath.Base(path)) - if err != nil { - return err - } - _, err = io.Copy(part, file) - - return err -} - -/// Prevent trying to import "fmt" -func reportError(format string, a ...interface{}) (error) { - return fmt.Errorf(format, a...) -} - -/// Set request body from an interface{} -func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { - if bodyBuf == nil { - bodyBuf = &bytes.Buffer{} - } - - if reader, ok := body.(io.Reader); ok { - _, err = bodyBuf.ReadFrom(reader) - } else if b, ok := body.([]byte); ok { - _, err = bodyBuf.Write(b) - } else if s, ok := body.(string); ok { - _, err = bodyBuf.WriteString(s) - } else if jsonCheck.MatchString(contentType) { - err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { - xml.NewEncoder(bodyBuf).Encode(body) - } - - if err != nil { - return nil, err - } - - if bodyBuf.Len() == 0 { - err = fmt.Errorf("Invalid body type %s\n", contentType) - return nil, err - } - return bodyBuf, nil -} - -/// detectContentType method is used to figure out `Request.Body` content type for request header -func detectContentType(body interface{}) string { - contentType := "text/plain; charset=utf-8" - kind := reflect.TypeOf(body).Kind() - - switch kind { - case reflect.Struct, reflect.Map, reflect.Ptr: - contentType = "application/json; charset=utf-8" - case reflect.String: - contentType = "text/plain; charset=utf-8" - default: - if b, ok := body.([]byte); ok { - contentType = http.DetectContentType(b) - } else if kind == reflect.Slice { - contentType = "application/json; charset=utf-8" - } - } - - return contentType -} - - -/// Ripped from https:///github.com/gregjones/httpcache/blob/master/httpcache.go -type cacheControl map[string]string - -func parseCacheControl(headers http.Header) cacheControl { - cc := cacheControl{} - ccHeader := headers.Get("Cache-Control") - for _, part := range strings.Split(ccHeader, ",") { - part = strings.Trim(part, " ") - if part == "" { - continue - } - if strings.ContainsRune(part, '=') { - keyval := strings.Split(part, "=") - cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") - } else { - cc[part] = "" - } - } - return cc -} - -/// CacheExpires helper function to determine remaining time before repeating a request. -func CacheExpires(r *http.Response) (time.Time) { - /// Figure out when the cache expires. - var expires time.Time - now, err := time.Parse(time.RFC1123, r.Header.Get("date")) - if err != nil { - return time.Now() - } - respCacheControl := parseCacheControl(r.Header) - - if maxAge, ok := respCacheControl["max-age"]; ok { - lifetime, err := time.ParseDuration(maxAge + "s") - if err != nil { - expires = now - } - expires = now.Add(lifetime) - } else { - expiresHeader := r.Header.Get("Expires") - if expiresHeader != "" { - expires, err = time.Parse(time.RFC1123, expiresHeader) - if err != nil { - expires = now - } - } - } - return expires -} - -func strlen(s string) (int) { - return utf8.RuneCountInString(s) -} - From 203069e9a93a3b7185362faaa372424510cc4d84 Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Sat, 5 Aug 2017 09:53:49 -0500 Subject: [PATCH 3/6] rust: Regenerate sample --- samples/client/petstore/rust/README.md | 2 +- samples/client/petstore/rust/docs/Pet.md | 4 +- samples/client/petstore/rust/docs/PetApi.md | 16 +-- samples/client/petstore/rust/docs/StoreApi.md | 8 +- samples/client/petstore/rust/docs/UserApi.md | 8 +- .../client/petstore/rust/src/apis/client.rs | 19 ++- samples/client/petstore/rust/src/apis/mod.rs | 9 +- .../client/petstore/rust/src/apis/pet_api.rs | 122 ++++++++++++------ .../petstore/rust/src/apis/store_api.rs | 50 ++++--- .../client/petstore/rust/src/apis/user_api.rs | 108 +++++++++++----- .../client/petstore/rust/src/models/mod.rs | 3 + .../client/petstore/rust/src/models/pet.rs | 12 +- 12 files changed, 231 insertions(+), 130 deletions(-) diff --git a/samples/client/petstore/rust/README.md b/samples/client/petstore/rust/README.md index 32ad5365bdf..ee5f2426813 100644 --- a/samples/client/petstore/rust/README.md +++ b/samples/client/petstore/rust/README.md @@ -1,4 +1,4 @@ -# Go API client for swagger +# Rust API client for swagger This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. diff --git a/samples/client/petstore/rust/docs/Pet.md b/samples/client/petstore/rust/docs/Pet.md index 21fd85091d5..ab2bef92432 100644 --- a/samples/client/petstore/rust/docs/Pet.md +++ b/samples/client/petstore/rust/docs/Pet.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **i64** | | [optional] [default to null] -**category** | [***::models::category::Category**](Category.md) | | [optional] [default to null] +**category** | [***::models::Category**](Category.md) | | [optional] [default to null] **name** | **String** | | [default to null] **photo_urls** | **Vec** | | [default to null] -**tags** | [**Vec<::models::tag::Tag>**](Tag.md) | | [optional] [default to null] +**tags** | [**Vec<::models::Tag>**](Tag.md) | | [optional] [default to null] **status** | **String** | pet status in the store | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/rust/docs/PetApi.md b/samples/client/petstore/rust/docs/PetApi.md index 275f6810e17..82e8a231c37 100644 --- a/samples/client/petstore/rust/docs/PetApi.md +++ b/samples/client/petstore/rust/docs/PetApi.md @@ -80,7 +80,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **FindPetsByStatus** -> Vec<::models::pet::Pet> FindPetsByStatus(ctx, status) +> Vec<::models::Pet> FindPetsByStatus(ctx, status) Finds Pets by status Multiple status values can be provided with comma separated strings @@ -94,7 +94,7 @@ Name | Type | Description | Notes ### Return type -[**Vec<::models::pet::Pet>**](Pet.md) +[**Vec<::models::Pet>**](Pet.md) ### Authorization @@ -108,7 +108,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **FindPetsByTags** -> Vec<::models::pet::Pet> FindPetsByTags(ctx, tags) +> Vec<::models::Pet> FindPetsByTags(ctx, tags) Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -122,7 +122,7 @@ Name | Type | Description | Notes ### Return type -[**Vec<::models::pet::Pet>**](Pet.md) +[**Vec<::models::Pet>**](Pet.md) ### Authorization @@ -136,7 +136,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GetPetById** -> ::models::pet::Pet GetPetById(ctx, pet_id) +> ::models::Pet GetPetById(ctx, pet_id) Find pet by ID Returns a single pet @@ -150,7 +150,7 @@ Name | Type | Description | Notes ### Return type -[**::models::pet::Pet**](Pet.md) +[**::models::Pet**](Pet.md) ### Authorization @@ -230,7 +230,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **UploadFile** -> ::models::api_response::ApiResponse UploadFile(ctx, pet_id, optional) +> ::models::ApiResponse UploadFile(ctx, pet_id, optional) uploads an image @@ -254,7 +254,7 @@ Name | Type | Description | Notes ### Return type -[**::models::api_response::ApiResponse**](ApiResponse.md) +[**::models::ApiResponse**](ApiResponse.md) ### Authorization diff --git a/samples/client/petstore/rust/docs/StoreApi.md b/samples/client/petstore/rust/docs/StoreApi.md index 7d38e21f421..f2c523db474 100644 --- a/samples/client/petstore/rust/docs/StoreApi.md +++ b/samples/client/petstore/rust/docs/StoreApi.md @@ -62,7 +62,7 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GetOrderById** -> ::models::order::Order GetOrderById(order_id) +> ::models::Order GetOrderById(order_id) Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -75,7 +75,7 @@ Name | Type | Description | Notes ### Return type -[**::models::order::Order**](Order.md) +[**::models::Order**](Order.md) ### Authorization @@ -89,7 +89,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **PlaceOrder** -> ::models::order::Order PlaceOrder(body) +> ::models::Order PlaceOrder(body) Place an order for a pet @@ -102,7 +102,7 @@ Name | Type | Description | Notes ### Return type -[**::models::order::Order**](Order.md) +[**::models::Order**](Order.md) ### Authorization diff --git a/samples/client/petstore/rust/docs/UserApi.md b/samples/client/petstore/rust/docs/UserApi.md index 4a1d691760c..1ae4ba43937 100644 --- a/samples/client/petstore/rust/docs/UserApi.md +++ b/samples/client/petstore/rust/docs/UserApi.md @@ -51,7 +51,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Vec<::models::user::User>**](User.md)| List of user object | + **body** | [**Vec<::models::User>**](User.md)| List of user object | ### Return type @@ -78,7 +78,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Vec<::models::user::User>**](User.md)| List of user object | + **body** | [**Vec<::models::User>**](User.md)| List of user object | ### Return type @@ -123,7 +123,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GetUserByName** -> ::models::user::User GetUserByName(username) +> ::models::User GetUserByName(username) Get user by user name @@ -136,7 +136,7 @@ Name | Type | Description | Notes ### Return type -[**::models::user::User**](User.md) +[**::models::User**](User.md) ### Authorization diff --git a/samples/client/petstore/rust/src/apis/client.rs b/samples/client/petstore/rust/src/apis/client.rs index c239fc77a76..9c4acd8f129 100644 --- a/samples/client/petstore/rust/src/apis/client.rs +++ b/samples/client/petstore/rust/src/apis/client.rs @@ -2,13 +2,12 @@ use std::rc::Rc; use hyper; use super::configuration::Configuration; -use super::pet_api; pub struct APIClient { configuration: Rc>, - pet_api: Box, - store_api: Box, - user_api: Box, + pet_api: Box<::apis::PetApi>, + store_api: Box<::apis::StoreApi>, + user_api: Box<::apis::UserApi>, } impl APIClient { @@ -17,21 +16,21 @@ impl APIClient { APIClient { configuration: rc.clone(), - pet_api: Box::new(pet_api::PetApiImpl::new(rc.clone())), - store_api: Box::new(store_api::StoreApiImpl::new(rc.clone())), - user_api: Box::new(user_api::UserApiImpl::new(rc.clone())), + pet_api: Box::new(::apis::PetApiImpl::new(rc.clone())), + store_api: Box::new(::apis::StoreApiImpl::new(rc.clone())), + user_api: Box::new(::apis::UserApiImpl::new(rc.clone())), } } - pub fn pet_api(&self) -> &pet_api::PetApi{ + pub fn pet_api(&self) -> &::apis::PetApi{ self.pet_api.as_ref() } - pub fn store_api(&self) -> &store_api::StoreApi{ + pub fn store_api(&self) -> &::apis::StoreApi{ self.store_api.as_ref() } - pub fn user_api(&self) -> &user_api::UserApi{ + pub fn user_api(&self) -> &::apis::UserApi{ self.user_api.as_ref() } diff --git a/samples/client/petstore/rust/src/apis/mod.rs b/samples/client/petstore/rust/src/apis/mod.rs index 4dd5322506b..fb706c84e2f 100644 --- a/samples/client/petstore/rust/src/apis/mod.rs +++ b/samples/client/petstore/rust/src/apis/mod.rs @@ -22,17 +22,14 @@ impl From for Error { use super::models::*; mod pet_api; - pub use self::pet_api::PetApi; - +pub use self::pet_api::PetApiImpl; mod store_api; - pub use self::store_api::StoreApi; - +pub use self::store_api::StoreApiImpl; mod user_api; - pub use self::user_api::UserApi; - +pub use self::user_api::UserApiImpl; pub mod configuration; pub mod client; diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index 306787088b3..913818bcc28 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -31,29 +31,34 @@ impl PetApiImpl { } pub trait PetApi { - fn AddPet(&self, body: Pet) -> Box>; + fn AddPet(&self, body: ::models::Pet) -> Box>; fn DeletePet(&self, pet_id: i64, api_key: &str) -> Box>; - fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>>; - fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>>; - fn GetPetById(&self, pet_id: i64) -> Box>; - fn UpdatePet(&self, body: Pet) -> Box>; + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>>; + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>>; + fn GetPetById(&self, pet_id: i64) -> Box>; + fn UpdatePet(&self, body: ::models::Pet) -> Box>; fn UpdatePetWithForm(&self, pet_id: i64, name: &str, status: &str) -> Box>; - fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box>; + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box>; } implPetApi for PetApiImpl { - fn AddPet(&self, body: Pet) -> Box> { + fn AddPet(&self, body: ::models::Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/pet", configuration.base_path); + let uri_str = format!("{}/pet", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -71,12 +76,19 @@ implPetApi for PetApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let mut headers = req.headers_mut(); - headers.set_raw("api_key", api_key); + { + let mut headers = req.headers_mut(); + headers.set_raw("api_key", api_key); + } // send request @@ -87,17 +99,22 @@ implPetApi for PetApiImpl { ) } - fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("status", status) + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("status", &status.join(",").to_string()) .finish(); - let uri = format!("{}/pet/findByStatus{}", configuration.base_path, query); + let uri_str = format!("{}/pet/findByStatus{}", configuration.base_path, query); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -106,23 +123,28 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result, _> = serde_json::from_slice(&body); + let parsed: Result, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("tags", tags) + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("tags", &tags.join(",").to_string()) .finish(); - let uri = format!("{}/pet/findByTags{}", configuration.base_path, query); + let uri_str = format!("{}/pet/findByTags{}", configuration.base_path, query); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -131,20 +153,25 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result, _> = serde_json::from_slice(&body); + let parsed: Result, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn GetPetById(&self, pet_id: i64) -> Box> { + fn GetPetById(&self, pet_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -153,23 +180,28 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::pet::Pet, _> = serde_json::from_slice(&body); + let parsed: Result<::models::Pet, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn UpdatePet(&self, body: Pet) -> Box> { + fn UpdatePet(&self, body: ::models::Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Put; - let uri = format!("{}/pet", configuration.base_path); + let uri_str = format!("{}/pet", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -187,9 +219,14 @@ implPetApi for PetApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -201,14 +238,19 @@ implPetApi for PetApiImpl { ) } - fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box> { + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); + let uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -217,7 +259,7 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::api_response::ApiResponse, _> = serde_json::from_slice(&body); + let parsed: Result<::models::ApiResponse, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index 192c5feae59..47b815db3c2 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -33,8 +33,8 @@ impl StoreApiImpl { pub trait StoreApi { fn DeleteOrder(&self, order_id: &str) -> Box>; fn GetInventory(&self, ) -> Box, Error = Error>>; - fn GetOrderById(&self, order_id: i64) -> Box>; - fn PlaceOrder(&self, body: Order) -> Box>; + fn GetOrderById(&self, order_id: i64) -> Box>; + fn PlaceOrder(&self, body: ::models::Order) -> Box>; } @@ -44,9 +44,14 @@ implStoreApi for StoreApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -63,9 +68,14 @@ implStoreApi for StoreApiImpl { let method = hyper::Method::Get; - let uri = format!("{}/store/inventory", configuration.base_path); + let uri_str = format!("{}/store/inventory", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -80,14 +90,19 @@ implStoreApi for StoreApiImpl { ) } - fn GetOrderById(&self, order_id: i64) -> Box> { + fn GetOrderById(&self, order_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -96,23 +111,28 @@ implStoreApi for StoreApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::order::Order, _> = serde_json::from_slice(&body); + let parsed: Result<::models::Order, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn PlaceOrder(&self, body: Order) -> Box> { + fn PlaceOrder(&self, body: ::models::Order) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/store/order", configuration.base_path); + let uri_str = format!("{}/store/order", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -122,7 +142,7 @@ implStoreApi for StoreApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::order::Order, _> = serde_json::from_slice(&body); + let parsed: Result<::models::Order, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index e306db6cb1e..2b9b75aafbe 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -31,29 +31,34 @@ impl UserApiImpl { } pub trait UserApi { - fn CreateUser(&self, body: User) -> Box>; - fn CreateUsersWithArrayInput(&self, body: Vec<::models::user::User>) -> Box>; - fn CreateUsersWithListInput(&self, body: Vec<::models::user::User>) -> Box>; + fn CreateUser(&self, body: ::models::User) -> Box>; + fn CreateUsersWithArrayInput(&self, body: Vec<::models::User>) -> Box>; + fn CreateUsersWithListInput(&self, body: Vec<::models::User>) -> Box>; fn DeleteUser(&self, username: &str) -> Box>; - fn GetUserByName(&self, username: &str) -> Box>; + fn GetUserByName(&self, username: &str) -> Box>; fn LoginUser(&self, username: &str, password: &str) -> Box>; fn LogoutUser(&self, ) -> Box>; - fn UpdateUser(&self, username: &str, body: User) -> Box>; + fn UpdateUser(&self, username: &str, body: ::models::User) -> Box>; } implUserApi for UserApiImpl { - fn CreateUser(&self, body: User) -> Box> { + fn CreateUser(&self, body: ::models::User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user", configuration.base_path); + let uri_str = format!("{}/user", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -66,17 +71,22 @@ implUserApi for UserApiImpl { ) } - fn CreateUsersWithArrayInput(&self, body: Vec<::models::user::User>) -> Box> { + fn CreateUsersWithArrayInput(&self, body: Vec<::models::User>) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user/createWithArray", configuration.base_path); + let uri_str = format!("{}/user/createWithArray", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -89,17 +99,22 @@ implUserApi for UserApiImpl { ) } - fn CreateUsersWithListInput(&self, body: Vec<::models::user::User>) -> Box> { + fn CreateUsersWithListInput(&self, body: Vec<::models::User>) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user/createWithList", configuration.base_path); + let uri_str = format!("{}/user/createWithList", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -117,9 +132,14 @@ implUserApi for UserApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/user/{username}", configuration.base_path, username=username); + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -131,14 +151,19 @@ implUserApi for UserApiImpl { ) } - fn GetUserByName(&self, username: &str) -> Box> { + fn GetUserByName(&self, username: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/user/{username}", configuration.base_path, username=username); + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -147,7 +172,7 @@ implUserApi for UserApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::user::User, _> = serde_json::from_slice(&body); + let parsed: Result<::models::User, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) @@ -158,13 +183,18 @@ implUserApi for UserApiImpl { let method = hyper::Method::Get; - let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("username", username) - .append_pair("password", password) + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("username", &username.to_string()) + .append_pair("password", &password.to_string()) .finish(); - let uri = format!("{}/user/login{}", configuration.base_path, query); + let uri_str = format!("{}/user/login{}", configuration.base_path, query); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -184,9 +214,14 @@ implUserApi for UserApiImpl { let method = hyper::Method::Get; - let uri = format!("{}/user/logout", configuration.base_path); + let uri_str = format!("{}/user/logout", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -198,17 +233,22 @@ implUserApi for UserApiImpl { ) } - fn UpdateUser(&self, username: &str, body: User) -> Box> { + fn UpdateUser(&self, username: &str, body: ::models::User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Put; - let uri = format!("{}/user/{username}", configuration.base_path, username=username); + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); diff --git a/samples/client/petstore/rust/src/models/mod.rs b/samples/client/petstore/rust/src/models/mod.rs index b4495b6a5fc..b24024670b2 100644 --- a/samples/client/petstore/rust/src/models/mod.rs +++ b/samples/client/petstore/rust/src/models/mod.rs @@ -10,3 +10,6 @@ mod tag; pub use self::tag::Tag; mod user; pub use self::user::User; + +// TODO(farcaller): sort out files +pub struct File; diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index 95ec4c8cae9..213f5fd1851 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -13,10 +13,10 @@ #[derive(Debug, Serialize, Deserialize)] pub struct Pet { #[serde(rename = "id")] id: Option, - #[serde(rename = "category")] category: Option, + #[serde(rename = "category")] category: Option<::models::Category>, #[serde(rename = "name")] name: String, #[serde(rename = "photoUrls")] photo_urls: Vec, - #[serde(rename = "tags")] tags: Option>, + #[serde(rename = "tags")] tags: Option>, /// pet status in the store #[serde(rename = "status")] status: Option } @@ -43,11 +43,11 @@ impl Pet { self } - pub fn set_category(&mut self, category: ::models::category::Category) { + pub fn set_category(&mut self, category: ::models::Category) { self.category = Some(category); } - pub fn with_category(mut self, category: ::models::category::Category) -> Pet { + pub fn with_category(mut self, category: ::models::Category) -> Pet { self.category = Some(category); self } @@ -70,11 +70,11 @@ impl Pet { self } - pub fn set_tags(&mut self, tags: Vec<::models::tag::Tag>) { + pub fn set_tags(&mut self, tags: Vec<::models::Tag>) { self.tags = Some(tags); } - pub fn with_tags(mut self, tags: Vec<::models::tag::Tag>) -> Pet { + pub fn with_tags(mut self, tags: Vec<::models::Tag>) -> Pet { self.tags = Some(tags); self } From c2ea9cbc11f0d2df2a0d4987f50fe27674d62883 Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Sat, 5 Aug 2017 09:50:05 -0500 Subject: [PATCH 4/6] rust: Rename *Impl -> *Client --- .../src/main/resources/rust/api.mustache | 10 +++++----- .../src/main/resources/rust/client.mustache | 4 ++-- samples/client/petstore/rust/src/apis/client.rs | 8 ++++---- samples/client/petstore/rust/src/apis/pet_api.rs | 10 +++++----- samples/client/petstore/rust/src/apis/store_api.rs | 10 +++++----- samples/client/petstore/rust/src/apis/user_api.rs | 10 +++++----- 6 files changed, 26 insertions(+), 26 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 9941dc92277..811f8870448 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -9,13 +9,13 @@ use futures::{Future, Stream}; use super::{Error, configuration}; -pub struct {{{classname}}}Impl { +pub struct {{{classname}}}Client { configuration: Rc>, } -impl {{{classname}}}Impl { - pub fn new(configuration: Rc>) -> {{{classname}}}Impl { - {{{classname}}}Impl { +impl {{{classname}}}Client { + pub fn new(configuration: Rc>) -> {{{classname}}}Client { + {{{classname}}}Client { configuration: configuration, } } @@ -30,7 +30,7 @@ pub trait {{classname}} { } -impl{{classname}} for {{classname}}Impl { +impl{{classname}} for {{classname}}Client { {{#operations}} {{#operation}} fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { diff --git a/modules/swagger-codegen/src/main/resources/rust/client.mustache b/modules/swagger-codegen/src/main/resources/rust/client.mustache index 82294ec771a..faaea0dbd2f 100644 --- a/modules/swagger-codegen/src/main/resources/rust/client.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/client.mustache @@ -21,7 +21,7 @@ pub struct APIClient { impl APIClient { pub fn new(configuration: Configuration) -> APIClient { let rc = Rc::new(configuration); - + APIClient { configuration: rc.clone(), {{#apiInfo}} @@ -29,7 +29,7 @@ impl APIClient { {{#operations}} {{#operation}} {{#-last}} - {{classFilename}}: Box::new(::apis::{{classname}}Impl::new(rc.clone())), + {{classFilename}}: Box::new(::apis::{{classname}}Client::new(rc.clone())), {{/-last}} {{/operation}} {{/operations}} diff --git a/samples/client/petstore/rust/src/apis/client.rs b/samples/client/petstore/rust/src/apis/client.rs index 9c4acd8f129..de8387bfe59 100644 --- a/samples/client/petstore/rust/src/apis/client.rs +++ b/samples/client/petstore/rust/src/apis/client.rs @@ -13,12 +13,12 @@ pub struct APIClient { impl APIClient { pub fn new(configuration: Configuration) -> APIClient { let rc = Rc::new(configuration); - + APIClient { configuration: rc.clone(), - pet_api: Box::new(::apis::PetApiImpl::new(rc.clone())), - store_api: Box::new(::apis::StoreApiImpl::new(rc.clone())), - user_api: Box::new(::apis::UserApiImpl::new(rc.clone())), + pet_api: Box::new(::apis::PetApiClient::new(rc.clone())), + store_api: Box::new(::apis::StoreApiClient::new(rc.clone())), + user_api: Box::new(::apis::UserApiClient::new(rc.clone())), } } diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index 913818bcc28..7c8249585cf 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -18,13 +18,13 @@ use futures::{Future, Stream}; use super::{Error, configuration}; -pub struct PetApiImpl { +pub struct PetApiClient { configuration: Rc>, } -impl PetApiImpl { - pub fn new(configuration: Rc>) -> PetApiImpl { - PetApiImpl { +impl PetApiClient { + pub fn new(configuration: Rc>) -> PetApiClient { + PetApiClient { configuration: configuration, } } @@ -42,7 +42,7 @@ pub trait PetApi { } -implPetApi for PetApiImpl { +implPetApi for PetApiClient { fn AddPet(&self, body: ::models::Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index 47b815db3c2..f6165a22d45 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -18,13 +18,13 @@ use futures::{Future, Stream}; use super::{Error, configuration}; -pub struct StoreApiImpl { +pub struct StoreApiClient { configuration: Rc>, } -impl StoreApiImpl { - pub fn new(configuration: Rc>) -> StoreApiImpl { - StoreApiImpl { +impl StoreApiClient { + pub fn new(configuration: Rc>) -> StoreApiClient { + StoreApiClient { configuration: configuration, } } @@ -38,7 +38,7 @@ pub trait StoreApi { } -implStoreApi for StoreApiImpl { +implStoreApi for StoreApiClient { fn DeleteOrder(&self, order_id: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index 2b9b75aafbe..49925d7b336 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -18,13 +18,13 @@ use futures::{Future, Stream}; use super::{Error, configuration}; -pub struct UserApiImpl { +pub struct UserApiClient { configuration: Rc>, } -impl UserApiImpl { - pub fn new(configuration: Rc>) -> UserApiImpl { - UserApiImpl { +impl UserApiClient { + pub fn new(configuration: Rc>) -> UserApiClient { + UserApiClient { configuration: configuration, } } @@ -42,7 +42,7 @@ pub trait UserApi { } -implUserApi for UserApiImpl { +implUserApi for UserApiClient { fn CreateUser(&self, body: ::models::User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); From 04758bdd2350b19b83a1a25e2a007c1c10ece34c Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Sat, 5 Aug 2017 09:50:25 -0500 Subject: [PATCH 5/6] rust: one-line use line More in line with common style --- .../src/main/resources/rust/api_mod.mustache | 3 +-- samples/client/petstore/rust/src/apis/mod.rs | 9 +++------ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache index e9f0ac2ce01..5b62b897cdd 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache @@ -27,8 +27,7 @@ mod {{classFilename}}; {{#operations}} {{#operation}} {{#-last}} -pub use self::{{classFilename}}::{{classname}}; -pub use self::{{classFilename}}::{{classname}}Impl; +pub use self::{{classFilename}}::{ {{classname}}, {{classname}}Client }; {{/-last}} {{/operation}} {{/operations}} diff --git a/samples/client/petstore/rust/src/apis/mod.rs b/samples/client/petstore/rust/src/apis/mod.rs index fb706c84e2f..ebd01fe651a 100644 --- a/samples/client/petstore/rust/src/apis/mod.rs +++ b/samples/client/petstore/rust/src/apis/mod.rs @@ -22,14 +22,11 @@ impl From for Error { use super::models::*; mod pet_api; -pub use self::pet_api::PetApi; -pub use self::pet_api::PetApiImpl; +pub use self::pet_api::{ PetApi, PetApiClient }; mod store_api; -pub use self::store_api::StoreApi; -pub use self::store_api::StoreApiImpl; +pub use self::store_api::{ StoreApi, StoreApiClient }; mod user_api; -pub use self::user_api::UserApi; -pub use self::user_api::UserApiImpl; +pub use self::user_api::{ UserApi, UserApiClient }; pub mod configuration; pub mod client; From bce36be33757f500bb52e404ef14d259d34272b7 Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Sat, 5 Aug 2017 16:12:54 -0500 Subject: [PATCH 6/6] rust: Replace tabs (in java) with 4 spaces --- .../codegen/languages/RustClientCodegen.java | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index 5b593b58a77..15caa76a245 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -51,17 +51,17 @@ public RustClientCodegen() { setReservedWordsLowerCase( Arrays.asList( - "abstract", "alignof", "as", "become", "box", - "break", "const", "continue", "crate", "do", - "else", "enum", "extern", "false", "final", - "fn", "for", "if", "impl", "in", - "let", "loop", "macro", "match", "mod", - "move", "mut", "offsetof", "override", "priv", - "proc", "pub", "pure", "ref", "return", - "Self", "self", "sizeof", "static", "struct", - "super", "trait", "true", "type", "typeof", - "unsafe", "unsized", "use", "virtual", "where", - "while", "yield" + "abstract", "alignof", "as", "become", "box", + "break", "const", "continue", "crate", "do", + "else", "enum", "extern", "false", "final", + "fn", "for", "if", "impl", "in", + "let", "loop", "macro", "match", "mod", + "move", "mut", "offsetof", "override", "priv", + "proc", "pub", "pure", "ref", "return", + "Self", "self", "sizeof", "static", "struct", + "super", "trait", "true", "type", "typeof", + "unsafe", "unsized", "use", "virtual", "where", + "while", "yield" ) ); @@ -73,10 +73,10 @@ public RustClientCodegen() { languageSpecificPrimitives = new HashSet( Arrays.asList( - "i8", "i16", "i32", "i64", - "u8", "u16", "u32", "u64", - "f32", "f64", - "char", "bool", "String", "Vec", "File") + "i8", "i16", "i32", "i64", + "u8", "u16", "u32", "u64", + "f32", "f64", + "char", "bool", "String", "Vec", "File") ); instantiationTypes.clear(); @@ -386,7 +386,7 @@ public Map postProcessOperations(Map objs) { p.dataType = "::std::collections::HashMap"; } } else if (!languageSpecificPrimitives.contains(p.dataType)) { - // add super:: to model, e.g. super::pet + // add super:: to model, e.g. super::pet p.dataType = "super::" + p.dataType; } }*/