Skip to content

Commit 47242c5

Browse files
committed
Merge pull request #2697 from wing328/ruby_parameter_validation
[Ruby] Add parameter validation in method call
2 parents 0792ddc + 875414f commit 47242c5

File tree

14 files changed

+552
-100
lines changed

14 files changed

+552
-100
lines changed

modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ public class CodegenParameter {
2020
public Map<String, Object> allowableValues;
2121
public CodegenProperty items;
2222
public Map<String, Object> vendorExtensions;
23+
public Boolean hasValidation;
2324

2425
/**
2526
* Determines whether this parameter is mandatory. If the parameter is in "path",
@@ -120,6 +121,7 @@ public CodegenParameter copy() {
120121
output.items = this.items;
121122
}
122123
output.vendorExtensions = this.vendorExtensions;
124+
output.hasValidation = this.hasValidation;
123125
output.isBinary = this.isBinary;
124126
output.isByteArray = this.isByteArray;
125127
output.isString = this.isString;

modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ public int hashCode()
8686
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
8787
result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode());
8888
result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode());
89+
result = prime * result + ((hasValidation == null) ? 0 : hasValidation.hashCode());
8990
result = prime * result + ((isString == null) ? 0 : isString.hashCode());
9091
result = prime * result + ((isInteger == null) ? 0 : isInteger.hashCode());
9192
result = prime * result + ((isLong == null) ? 0 : isLong.hashCode());
@@ -203,12 +204,19 @@ public boolean equals(Object obj) {
203204
if (this.allowableValues != other.allowableValues && (this.allowableValues == null || !this.allowableValues.equals(other.allowableValues))) {
204205
return false;
205206
}
207+
206208
if (this.vendorExtensions != other.vendorExtensions && (this.vendorExtensions == null || !this.vendorExtensions.equals(other.vendorExtensions))) {
207209
return false;
208210
}
211+
212+
if (this.hasValidation != other.hasValidation && (this.hasValidation == null || !this.hasValidation.equals(other.hasValidation))) {
213+
return false;
214+
}
215+
209216
if (this.isString != other.isString && (this.isString == null || !this.isString.equals(other.isString))) {
210217
return false;
211218
}
219+
212220
if (this.isInteger != other.isInteger && (this.isInteger == null || !this.isInteger.equals(other.isInteger))) {
213221
return false;
214222
}

modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1833,6 +1833,15 @@ public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
18331833
p.minItems = qp.getMinItems();
18341834
p.uniqueItems = qp.isUniqueItems();
18351835
p.multipleOf = qp.getMultipleOf();
1836+
1837+
if (p.maximum != null || p.exclusiveMaximum != null ||
1838+
p.minimum != null || p.exclusiveMinimum != null ||
1839+
p.maxLength != null || p.minLength != null ||
1840+
p.maxItems != null || p.minItems != null ||
1841+
p.pattern != null) {
1842+
p.hasValidation = true;
1843+
}
1844+
18361845
} else {
18371846
if (!(param instanceof BodyParameter)) {
18381847
LOGGER.error("Cannot use Parameter " + param + " as Body Parameter");

modules/swagger-codegen/src/main/resources/ruby/api.mustache

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,59 @@ module {{moduleName}}
3333
{{/required}}{{/allParams}} # @return [Array<({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Fixnum, Hash)>] {{#returnType}}{{{returnType}}} data{{/returnType}}{{^returnType}}nil{{/returnType}}, response status code and response headers
3434
def {{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
3535
if @api_client.config.debugging
36-
@api_client.config.logger.debug "Calling API: {{classname}}#{{operationId}} ..."
36+
@api_client.config.logger.debug "Calling API: {{classname}}.{{operationId}} ..."
3737
end
38-
{{#allParams}}{{#required}}
38+
{{#allParams}}
39+
{{#required}}
3940
# verify the required parameter '{{paramName}}' is set
40-
fail "Missing the required parameter '{{paramName}}' when calling {{operationId}}" if {{{paramName}}}.nil?{{#isEnum}}
41+
fail ArgumentError, "Missing the required parameter '{{paramName}}' when calling {{classname}}.{{operationId}}" if {{{paramName}}}.nil?
42+
{{#isEnum}}
43+
# verify enum value
4144
unless [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?({{{paramName}}})
42-
fail "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"
43-
end{{/isEnum}}
44-
{{/required}}{{^required}}{{#isEnum}}
45+
fail ArgumentError, "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"
46+
end
47+
{{/isEnum}}
48+
{{/required}}
49+
{{^required}}
50+
{{#isEnum}}
4551
if opts[:'{{{paramName}}}'] && ![{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(opts[:'{{{paramName}}}'])
46-
fail 'invalid value for "{{{paramName}}}", must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}'
52+
fail ArgumentError, 'invalid value for "{{{paramName}}}", must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}'
53+
end
54+
{{/isEnum}}
55+
{{/required}}
56+
{{#hasValidation}}
57+
{{#minLength}}
58+
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length > {{{maxLength}}}
59+
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.'
60+
end
61+
62+
{{/minLength}}
63+
{{#maxLength}}
64+
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length < {{{minLength}}}
65+
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.'
66+
end
67+
68+
{{/maxLength}}
69+
{{#maximum}}
70+
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} > {{{maximum}}}
71+
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{{maximum}}}.'
4772
end
48-
{{/isEnum}}{{/required}}{{/allParams}}
73+
74+
{{/maximum}}
75+
{{#minimum}}
76+
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} < {{{minimum}}}
77+
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be greater than or equal to {{{minimum}}}.'
78+
end
79+
80+
{{/minimum}}
81+
{{#pattern}}
82+
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} !~ Regexp.new({{{pattern}}})
83+
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'
84+
end
85+
86+
{{/pattern}}
87+
{{/hasValidation}}
88+
{{/allParams}}
4989
# resource path
5090
local_var_path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}
5191

modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,96 @@ paths:
559559
description: Invalid username supplied
560560
'404':
561561
description: User not found
562+
563+
/fake:
564+
post:
565+
tags:
566+
- fake
567+
summary: Fake endpoint for testing various parameters
568+
description: Fake endpoint for testing various parameters
569+
operationId: testEndpointParameters
570+
produces:
571+
- application/xml
572+
- application/json
573+
parameters:
574+
- name: integer
575+
type: integer
576+
maximum: 100
577+
minimum: 10
578+
in: formData
579+
description: None
580+
- name: int32
581+
type: integer
582+
format: int32
583+
maximum: 200
584+
minimum: 20
585+
in: formData
586+
description: None
587+
- name: int64
588+
type: integer
589+
format: int64
590+
in: formData
591+
description: None
592+
- name: number
593+
maximum: 543.2
594+
minimum: 32.1
595+
in: formData
596+
description: None
597+
required: true
598+
- name: float
599+
type: number
600+
format: float
601+
maximum: 987.6
602+
in: formData
603+
description: None
604+
- name: double
605+
type: number
606+
in: formData
607+
format: double
608+
maximum: 123.4
609+
minimum: 67.8
610+
required: true
611+
description: None
612+
- name: string
613+
type: string
614+
pattern: /[a-z]/i
615+
in: formData
616+
description: None
617+
required: true
618+
- name: byte
619+
type: string
620+
format: byte
621+
in: formData
622+
description: None
623+
required: true
624+
- name: binary
625+
type: string
626+
format: binary
627+
in: formData
628+
description: None
629+
- name: date
630+
type: string
631+
format: date
632+
in: formData
633+
description: None
634+
- name: dateTime
635+
type: string
636+
format: date-time
637+
in: formData
638+
description: None
639+
- name: password
640+
type: string
641+
format: password
642+
maxLength: 64
643+
minLength: 10
644+
in: formData
645+
description: None
646+
responses:
647+
'400':
648+
description: Invalid username supplied
649+
'404':
650+
description: User not found
651+
562652
securityDefinitions:
563653
petstore_auth:
564654
type: oauth2

samples/client/petstore/ruby/README.md

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/
88

99
- API version: 1.0.0
1010
- Package version: 1.0.0
11-
- Build date: 2016-04-25T22:22:56.750+08:00
11+
- Build date: 2016-04-25T23:58:59.140+08:00
1212
- Build package: class io.swagger.codegen.languages.RubyClientCodegen
1313

1414
## Installation
@@ -55,22 +55,32 @@ Please follow the [installation](#installation) procedure and then run the follo
5555
# Load the gem
5656
require 'petstore'
5757

58-
# Setup authorization
59-
Petstore.configure do |config|
60-
# Configure OAuth2 access token for authorization: petstore_auth
61-
config.access_token = 'YOUR ACCESS TOKEN'
62-
end
58+
api_instance = Petstore::FakeApi.new
59+
60+
number = "number_example" # String | None
61+
62+
double = 1.2 # Float | None
6363

64-
api_instance = Petstore::PetApi.new
64+
string = "string_example" # String | None
6565

66-
body = Petstore::Pet.new # Pet | Pet object that needs to be added to the store
66+
byte = "B" # String | None
6767

68+
opts = {
69+
integer: 56, # Integer | None
70+
int32: 56, # Integer | None
71+
int64: 789, # Integer | None
72+
float: 3.4, # Float | None
73+
binary: "B", # String | None
74+
date: Date.parse("2013-10-20"), # Date | None
75+
date_time: DateTime.parse("2013-10-20T19:20:30+01:00"), # DateTime | None
76+
password: "password_example" # String | None
77+
}
6878

6979
begin
70-
#Add a new pet to the store
71-
api_instance.add_pet(body)
80+
#Fake endpoint for testing various parameters
81+
api_instance.test_endpoint_parameters(number, double, string, byte, opts)
7282
rescue Petstore::ApiError => e
73-
puts "Exception when calling PetApi->add_pet: #{e}"
83+
puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}"
7484
end
7585

7686
```
@@ -81,6 +91,7 @@ All URIs are relative to *http://petstore.swagger.io/v2*
8191

8292
Class | Method | HTTP request | Description
8393
------------ | ------------- | ------------- | -------------
94+
*Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters
8495
*Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store
8596
*Petstore::PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet
8697
*Petstore::PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Petstore::FakeApi
2+
3+
All URIs are relative to *http://petstore.swagger.io/v2*
4+
5+
Method | HTTP request | Description
6+
------------- | ------------- | -------------
7+
[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters
8+
9+
10+
# **test_endpoint_parameters**
11+
> test_endpoint_parameters(number, double, string, byte, opts)
12+
13+
Fake endpoint for testing various parameters
14+
15+
Fake endpoint for testing various parameters
16+
17+
### Example
18+
```ruby
19+
# load the gem
20+
require 'petstore'
21+
22+
api_instance = Petstore::FakeApi.new
23+
24+
number = "number_example" # String | None
25+
26+
double = 1.2 # Float | None
27+
28+
string = "string_example" # String | None
29+
30+
byte = "B" # String | None
31+
32+
opts = {
33+
integer: 56, # Integer | None
34+
int32: 56, # Integer | None
35+
int64: 789, # Integer | None
36+
float: 3.4, # Float | None
37+
binary: "B", # String | None
38+
date: Date.parse("2013-10-20"), # Date | None
39+
date_time: DateTime.parse("2013-10-20T19:20:30+01:00"), # DateTime | None
40+
password: "password_example" # String | None
41+
}
42+
43+
begin
44+
#Fake endpoint for testing various parameters
45+
api_instance.test_endpoint_parameters(number, double, string, byte, opts)
46+
rescue Petstore::ApiError => e
47+
puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}"
48+
end
49+
```
50+
51+
### Parameters
52+
53+
Name | Type | Description | Notes
54+
------------- | ------------- | ------------- | -------------
55+
**number** | **String**| None |
56+
**double** | **Float**| None |
57+
**string** | **String**| None |
58+
**byte** | **String**| None |
59+
**integer** | **Integer**| None | [optional]
60+
**int32** | **Integer**| None | [optional]
61+
**int64** | **Integer**| None | [optional]
62+
**float** | **Float**| None | [optional]
63+
**binary** | **String**| None | [optional]
64+
**date** | **Date**| None | [optional]
65+
**date_time** | **DateTime**| None | [optional]
66+
**password** | **String**| None | [optional]
67+
68+
### Return type
69+
70+
nil (empty response body)
71+
72+
### Authorization
73+
74+
No authorization required
75+
76+
### HTTP request headers
77+
78+
- **Content-Type**: Not defined
79+
- **Accept**: application/xml, application/json
80+
81+
82+

samples/client/petstore/ruby/lib/petstore.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
require 'petstore/models/user'
3838

3939
# APIs
40+
require 'petstore/api/fake_api'
4041
require 'petstore/api/pet_api'
4142
require 'petstore/api/store_api'
4243
require 'petstore/api/user_api'

0 commit comments

Comments
 (0)